如何打开文件夹中的每个文件?

我有一个python脚本parse.py,该脚本在脚本中打开一个文件,例如file1,然后执行一些操作,可能会打印出字符总数。


filename = 'file1'

f = open(filename, 'r')

content = f.read()

print filename, len(content)

现在,我正在使用stdout将结果定向到我的输出文件-输出


python parse.py >> output

但是,我不想按文件手动处理此文件,有没有办法自动处理每个文件?喜欢


ls | awk '{print}' | python parse.py >> output 

然后问题是如何从standardin中读取文件名?还是已经有一些内置功能可以轻松执行ls和此类工作?


谢谢!


慕村225694
浏览 571回答 3
3回答

拉莫斯之舞

你应该尝试使用os.walkyourpath = 'path'import osfor root, dirs, files in os.walk(yourpath, topdown=False):    for name in files:        print(os.path.join(root, name))        stuff    for name in dirs:        print(os.path.join(root, name))        stuff

猛跑小猪

实际上,您可以只使用os模块来完成这两项:列出文件夹中的所有文件按文件类型,文件名等对文件进行排序这是一个简单的例子:import os #os module imported herelocation = os.getcwd() # get present working directory location herecounter = 0 #keep a count of all files foundcsvfiles = [] #list to store all csv files found at locationfilebeginwithhello = [] # list to keep all files that begin with 'hello'otherfiles = [] #list to keep any other file that do not match the criteriafor file in os.listdir(location):    try:        if file.endswith(".csv"):            print "csv file found:\t", file            csvfiles.append(str(file))            counter = counter+1        elif file.startswith("hello") and file.endswith(".csv"): #because some files may start with hello and also be a csv file            print "csv file found:\t", file            csvfiles.append(str(file))            counter = counter+1        elif file.startswith("hello"):            print "hello files found: \t", file            filebeginwithhello.append(file)            counter = counter+1        else:            otherfiles.append(file)            counter = counter+1    except Exception as e:        raise e        print "No files found here!"print "Total files found:\t", counter现在,您不仅列出了文件夹中的所有文件,而且(可选)按起始名称,文件类型等对它们进行了排序。刚才遍历每个列表并做您的工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python