1
os.chdir(r"C:\Downloads")

I'm getting stuck with reading in files in Python. Why does specifying the relative file path not work when reading the file?

files = os.listdir(r"csvfilestoimport")
files
['file1.csv', 'file2.csv']
df1 = pd.concat([pd.read_csv(f) for f in files])
FileNotFoundError: [Errno 2] File file.csv does not exist:'file1.csv'

4
  • Does the file exist? In the second case you write to another filename. Commented Aug 15, 2020 at 10:29
  • In the first case, you are reading an existing file. In the second case you are creating a file Commented Aug 15, 2020 at 10:30
  • Yes I want to read an existing file, do some analysis and export as xlsx. The file exists in the folder since the full filepath works when reading the csv. Commented Aug 15, 2020 at 10:30
  • is the change of the current directory successful? what does os.getcwd() say after you run the command? Commented Aug 15, 2020 at 10:33

4 Answers 4

1

os was my choice before I learned about pathlib.


from pathlib import Path


path = Path("C:\Downloads")
df = pd.concat([pd.read_csv(f) for f in path.rglob("*.csv")])

With pathlib you don't have to join directory and file manually.

Sign up to request clarification or add additional context in comments.

Comments

1

Try creating a new file with a name you are sure that doesn't exist before (in your entire computer), and check that it is created in the folder you think. Then try to read it.

Ok, now with your example. Please, note that

files = os.listdir(r"csvfilestoimport")
['file1.csv', 'file2.csv']

really means

['csvfilestoimport\file1.csv', 'csvfilestoimport\file2.csv']

So, you need to add this folder (r"csvfilestoimport"+f)

df1 = pd.concat([pd.read_csv(r"csvfilestoimport\"+f) for f in files])

1 Comment

I'm getting: SyntaxError: EOL while scanning string literal
1

See this eg.

root_path = r"C:\Downloads"
filelist = glob.glob(f"{root_path}//*.csv")
df1 = pd.concat([pd.read_csv(f) for f in filelist])

Comments

0

In OS.chdir() try giving the full path of the downloads "C:\Users\xxxx\Downloads" and try again

os.chdir(r'C:\Users\xxxxx\Downloads')

1 Comment

if your code is not in the same folder where your source file is, then while changing the directory you should mention that in full

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.