读取目录中的所有csv文件

时间:2016-12-30 06:29:36

标签: python-3.x csv

我在目录中有CSV文件,我想打开它们中的每一个并阅读第一列。这是我的代码:

directory = os.path.join("c:\\","/Users/user/My Documents/test/")
 for root,dirs,files in os.walk(directory):
    for file in files:
           f = open(file, 'r')
           reader = csv.reader(f)
           for row in reader:
                print(row[0])

当我运行它时,我收到了一个错误:

FileNotFoundError: [Errno 2] No such file or directory : 'file1.csv'

任何想法为什么?

2 个答案:

答案 0 :(得分:0)

我弄清楚如何解决它:

 directory = os.listdir('/Users/user/My Documents/test/')
 os.chdir('/Users/user/My Documents/test/')
 for files in directory:
           with open(files, 'r')as f:
            reader = csv.reader(f)
            for row in reader:
                print(row[0])

答案 1 :(得分:0)

这种情况正在发生,因为os.walk也递归遍历所有子目录。因此,您的代码不应该假设所有文件都位于当前目录中。

directory = os.path.join("c:\\","/Users/user/My Documents/test/")
for root,dirs,files in os.walk(directory):
    for file in files:
       f = open(os.path.join(root, file), 'r') # I have considered root path too
       reader = csv.reader(f)
       for row in reader:
            print(row[0])