Lucas Fernandez
Lucas Fernandez

Reputation: 96

File not found error when it should create it (only when I add the current date to the name)

I'm trying to create a .csv file with some scraped data that enters the function as the "results" argument. The problem is when i add the current system date to the name of the file, I get a "file not found error" when the result I expect is a file to be created.

Here's my code:

def saveData(results):
    date = datetime.today().strftime('%d/%m/%Y')
    file = pathlib.Path(f'Results-{date}.csv')
    with open(file,'w',newline='') as f:
        writer = csv.writer(f)
        for result in results:
            if result:
                writer.writerow(result)
        print('File written')


saveData(scrapedData(urlList()))

And the Error that I am getting:

line 99, in saveData
with open(file,'w',newline='') as f:

FileNotFoundError: [Errno 2] No such file or directory: 'Results-13\\02\\2020.csv'

Please note that I do not get this error when I remove the date from the file name.

Thank you.

Upvotes: 2

Views: 264

Answers (1)

Tupteq
Tupteq

Reputation: 3095

You have slashes (/) in your file name. They are converted to backslashes (you're probably a Windows user) and they are treated as path separators. So, open() tries to create a file deep in non existing directory tree.

Just replace slashes by some other character (avoid * and other special characters).

Upvotes: 3

Related Questions