为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕村225694 2019-11-05 16:30:48
我有一个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和此类工作?谢谢!
查看完整描述

3 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

你应该尝试使用os.walk


yourpath = 'path'


import os

for 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


查看完整回答
反对 回复 2019-11-05
?
猛跑小猪

TA贡献1858条经验 获得超8个赞

实际上,您可以只使用os模块来完成这两项:


列出文件夹中的所有文件

按文件类型,文件名等对文件进行排序

这是一个简单的例子:

import os #os module imported here

location = os.getcwd() # get present working directory location here

counter = 0 #keep a count of all files found

csvfiles = [] #list to store all csv files found at location

filebeginwithhello = [] # list to keep all files that begin with 'hello'

otherfiles = [] #list to keep any other file that do not match the criteria


for 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

现在,您不仅列出了文件夹中的所有文件,而且(可选)按起始名称,文件类型等对它们进行了排序。刚才遍历每个列表并做您的工作。


查看完整回答
反对 回复 2019-11-05
  • 3 回答
  • 0 关注
  • 541 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信