简体   繁体   English

python:将文件读入数据帧时出错

[英]python: error reading files into data frame

I'm trying to import multiple csv files in one folder into one data frame.我正在尝试将一个文件夹中的多个 csv 文件导入一个数据帧。 This is my code.这是我的代码。 It can iterate through the files and print them successfully and it can read one file into a data frame but combining them is printing an error.它可以遍历文件并成功打印它们,它可以将一个文件读入数据框,但将它们组合起来会打印错误。 I saw many questions similar but the responses are complex, I thought the 'pythonic' way is to be simple because I am new to this.我看到很多类似的问题,但回答很复杂,我认为“pythonic”的方式很简单,因为我是新手。 Thanks in advance for any help.提前感谢您的帮助。 The error message is always: No such file or directory: 'some file name' which makes no sense because it successfully printed the file name in the print step.错误消息始终是:没有这样的文件或目录:'some file name' 这没有意义,因为它在打印步骤中成功打印了文件名。

import pandas as pd   

# this works
df = pd.read_csv("headlines/2017-1.csv") 
print(df)

path = 'C:/.../... /.../headlines/'  <--- full path I shortened it here
files = os.listdir(path)   
print(files)     <-- prints all file names successfully

for filename in files:
    print(filename)   # <-- successfully prints all file names
    df = pd.read_csv(filename)  # < -- error here
    df2.append(df) # append to data frame

It seems like your current working directory is different from your path .您当前的工作目录似乎与您的path不同。 Please use os.chdir(path) before attempting to read your csv.请在尝试读取 csv 之前使用os.chdir(path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM