打开CSV目录中的所有文件并读取Python的每一行

2024-10-01 07:33:44 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在找一些关于我的问题的帮助。我只想在数据所在的目录(如下所示)中搜索特定的文件类型。下面是我的代码,但它不能正常工作。在

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

好吧,这就是我想做的。我只想搜索目录中列出的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

谢谢你的帮助。在


Tags: 文件csv代码in目录forosline
1条回答
网友
1楼 · 发布于 2024-10-01 07:33:44

以下代码有效。我已经评论了什么修改内联。在

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()

相关问题 更多 >