您好,我正在寻求有关我遇到的问题的帮助。我想在我的数据所在的目录(如下所示)中仅搜索某些文件类型。下面是我的代码,但它不能正常工作。
当前输出是两个结果之一。它要么只打印文件的第一行,要么只打印空白结果。
好的,这就是我想做的。我想搜索仅列出的 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
感谢您的帮助。
最佳答案
下面的代码有效。我已经评论了内联修改的内容。
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()
关于python - 打开 CSV 目录中的所有文件并读取每一行 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17246563/