Search code examples
pythonfileshutilfile-copying

Errno 22 Invalid Argument Python


I'm trying to copy one file's content to another, and error appears, what do i do wrong?

for file in os.listdir('offer'):
    if '.css' in file:
        print(file)
        with open(f'offer/{file}', 'r+') as f:
            with open('offer/id.css', 'w+') as style_file:
                shutil.copyfile(f'offer/{f}', f'offer/{style_file}')
Traceback (most recent call last):
  File "C:/Users/Katerina/Desktop/python/test_attempt.py", line 50, in <module>
    shutil.copyfile(f'offer/{f}', f'offer/{style_file}')
  File "C:\Users\Katerina\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 120, in copyfile
    with open(src, 'rb') as fsrc:
OSError: [Errno 22] Invalid argument: "offer/<_io.TextIOWrapper name='offer/id.css' mode='r+' encoding='cp1251'>"

Solution

  • I guess you are looking for something like

    with open('offer/id.css', 'w') as style_file:
        for file in os.listdir('offer'):
            if '.css' in file:
                #print(file)
                with open(f'offer/{file}', 'r+') as f:
                    for line in f:
                        style_file.write(line)
    

    The purpose of shutil.copyfile is different; it doesn't really allow you to access or modify the contents of either file, it just copies one to the other.