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'
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])
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])
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.
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.