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

标签 python csv directory readlines

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

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

好的,这就是我想做的。我想搜索仅列出的 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/

相关文章:

php - 使用 php 搜索和删除文章中未使用的图像

java - 删除Java中的所有空文件夹

python - (ε, δ)-差分隐私准确性/隐私权衡

python - python 正则表达式分组的最佳实践

php - 使用 PHP 代码和 HTML 表单将 excel (.csv) 导入 MySQL

MySQL:可选地包含在 '"' 中断 INTO OUTFILE 变量名

csv - 如何从我的 CSV 中选择哪些列来使用 HighChart 绘制图表?

java - 无法在 Java 中播放声音

python - 类似 Xpath 的嵌套 python 字典查询

python - 在 mac os 和 python 中设置 SIGKILL 处理程序时出现 OSError