【问题标题】:Opening all files in a directory for CSV and reading each line Python为 CSV 打开目录中的所有文件并读取每一行 Python
【发布时间】:2013-06-19 06:04:39
【问题描述】:

您好,我正在就遇到的问题寻求帮助。我想仅在某些文件类型中搜索我的数据所在的目录(如下所示)。下面是我的代码,但它不能正常工作。

当前输出是两个结果之一。要么只打印文件的第一行,要么只打印空白结果。

好的,这就是我想要做的。我想搜索仅列出 csv 文件的目录。然后我想做的是让循环逐行读取每个文件并打印文件中的每一行,然后对其余的 csv 文件重复此操作。

谁能告诉我如何编辑下面的代码以仅搜索 CSV 文件,以及如何打印文件中的每一行,然后重复下一个 CSV 文件,直到找到并打开所有 CSV 文件。这可能吗?

import os

rootdir= 'C:\Documents and Settings\Guest\My Documents\Code'

def doWhatYouWant(line):
    print line

for subdir, dirs, files in os.walk(rootdir):
   for file in files:
        f=open(file,'r')
        lines = f.readlines()
        f.close()
        f=open(file,'wU')
        for lines in lines:
            newline=doWhatYouWant(line)
            f.write(newline)
        f.close

感谢您的帮助。

【问题讨论】:

  • 您需要在rootdir 字符串中添加r 前缀,以防止反斜杠被解释为转义字符。为了只处理 CSV 文件,您可以使用 my answer 来解决相关问题,除了使用 '*.csv' 作为模式而不是显示的模式。此外,最后,您需要一个 f.close() 来实际调用该方法。

标签: python csv directory readlines


【解决方案1】:

以下代码有效。我已经评论了内联修改的内容。

import os

rootdir= 'C:\\Documents\ and\ Settings\\Guest\\My\ Documents\\Code\\' 
#use '\\' in a normal string if you mean to make it be a '\'   
#use '\ ' in a normal string if you mean to make it be a ' '   


def doWhatYouWant(line):
    print line
    return line 
    #let the function return, not only print, to get the value for use as below 


for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        f=open(rootdir+file,'r') #use the absolute URL of the file
        lines = f.readlines()
        f.close()
        f=open(file,'w') #universal mode can only be used with 'r' mode
        for line in lines:
            newline=doWhatYouWant(line)
            f.write(newline)
        f.close()

【讨论】:

  • 感谢@Skyler 我刚刚尝试实现此功能,但出现以下错误。回溯(最近一次通话最后):文件“C:/Documents and Settings/Guest/My Documents/SC/Actual work/Part2/New Folder/New Folder/ohno.py”,第 13 行,在 f=open (rootdir+file,'r') #使用文件的绝对URL IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\Guest\\My Documents\\SC\\Actual工作\\Part2\\新文件夹4033_1800_Data.csv'
  • 那是因为你的 URL 太复杂了。您可以尝试使 URL 干净吗?没有空格或特殊字符。
  • 以 C:\Documents and Settings\Guest\My Documents\ABC 为例会不会更好?
  • 我没有windows系统可以试用。您可能只想先尝试“C:\\ABC\\”看看会发生什么。
  • 嗯@Skyler 确实有一点帮助,但不是我想要的,但还是谢谢
猜你喜欢
  • 2016-02-03
  • 1970-01-01
  • 2011-05-31
  • 2012-09-29
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多