1

I'm trying to make a new .csv file, but I'm getting a "No such file or directory" in the with open(...) portion of the code.

I modified the with open(...) portion of the code to exclude a direction, substituting a string name, and it worked just fine. The document was created with all my PyCharm scratches on the C Drive.

I believe it's worth noting that I'm running python on my C: Drive while the directory giving me issues exists on the D: Drive. Not sure if that actually makes a difference, but i

path = r"D:\Folder_Location\\"
plpath = pathlib.PurePath(path)
files = []
csv_filename = r"D:\Folder_Location\\"+str(plpath.name)+".csv"

#Create New CSV
with open(csv_filename, mode='w',newline='') as c:
    writer = csv.writer(c)
    writer.writerow(['Date','Name'])

I expected the code to create a new .csv file that would then be used by the rest of the script in the specific folder location, but instead I got the following error:

  File "C:/Users/USER/.PyCharm2018.2/config/scratches/file.py", line 14, in <module>
    with open(csv_filename, mode='w',newline='') as c:
FileNotFoundError: [Errno 2] No such file or directory: '[INTENDED FILE NAME]'

Process finished with exit code 1

The error code correctly builds the file name, but then says that it can't find the location, leading me to believe, again, that it's not the code itself but an issue with the separate drives (speculating). Also, line 14 is where the with open(...) starts.

EDIT: I tested a theory, and moved the folder to the C: drive, updated the path with just a copy and paste from the new location (still using the \ at the end of the file path in Python), and it worked. The new .csv file is now there. So why would the Drive make a difference? Permission issue for Python?

12
  • 1
    Look at the path in the error and then check out the path that you wrote in the code. Can you notice a significant difference? ;) Commented May 14, 2019 at 22:44
  • Does the directory exist? Commented May 14, 2019 at 22:44
  • 1
    @alfasin They clearly just redacted it. Commented May 14, 2019 at 22:45
  • 2
    You use r-prefix for path string and double backslash in it. This means there is then a real double backslash in the path. Commented May 14, 2019 at 22:46
  • @MichaelButscher for whatever reason, if the path ends with a backslash, it errors out. I do the \\ on all of my other code and it works just fine. Do you think it's just the code or how the code is being use that's causing the issue? Commented May 14, 2019 at 22:48

2 Answers 2

1

The raw string can not end with one single backslash '\' so what you are using in your code like in path = r"D:\Folder_Location\\" is the right thing but actually you don't need any backslashes at the end of your path:

i ran some similar tests like yours and all goes well, only got the same error when i used a non existing directory

this is what i got:

FileNotFoundError: [Errno 2] No such file or directory: 'E:\\python\\myProgects\\abc\\\\sample3.txt'

so my bet is you have a non existing path assigned in path = r"D:\Folder_Location\\" or your path is referring to a file not a folder to make sure just run this:

import os
path = r"D:\Folder_Location\\"
print(os.path.isdir(path))  # print true if folder already exists

better approach:

file_name = str(plpath.name)+".csv"
path = r"D:\Folder_Location"
csv_filename = os.path.join(path, file_name)
Sign up to request clarification or add additional context in comments.

2 Comments

I'll give that a shot. Any idea about why it would work as is on the C: Drive but not the D: Drive?
It make no difference which drive you use, I believe your folder in d is not exist or your path is a file not a folder, you will find out once you get the output of ‘print(os.path.isdir(path))’
0

When we physically create a new file, we may need to separate the creation of the folder directory (if it does not exist) from the file creation transaction.

In this way, we ensure that we do not encounter the conflict of whether the relevant directory exists or not during file creation.

I prepared an example of this method as follows:

import os, csv
from typing import List

def create_folder(folder_path):
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

def create_csv(directory:str, file_name:str, has_headers:bool, headers:List[str]=[]):
    create_folder(directory) 
    if os.path.exists(directory):
        file_path = f'{directory}\\{file_name}.csv'
        if not os.path.exists(file_path):
            with open(file_path, mode='w', encoding="utf-8", newline='') as file:
                writer = csv.writer(file, delimiter=',')
                if has_headers and len(headers) > 0:
                    writer.writerow(headers)
                
                print(file_path)


create_csv(os.path.join(os.getcwd(), 'my_folder'), 
           'test_file',True, ['column_1', 'column_2', 'column_3'])

I hope it will be useful for your project.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.