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

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

本文介绍了如何打开文件夹中的每个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a python script parse.py, which in the script open a file, say file1, and then do something maybe print out the total number of characters.

filename = 'file1'
f = open(filename, 'r')
content = f.read()
print filename, len(content)

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

Right now, I am using stdout to direct the result to my output file - output

python parse.py >> output

但是,我不想按文件手动处理此文件,有没有一种方法可以自动处理每个文件?喜欢

However, I don't want to do this file by file manually, is there a way to take care of every single file automatically? Like

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

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

Then the problem is how could I read the file name from standardin?or there are already some built-in functions to do the ls and those kind of work easily?

谢谢!

推荐答案

操作系统

您可以使用 os.listdir 列出当前目录中的所有文件:

You can list all files in the current directory using os.listdir:

import os
for filename in os.listdir(os.getcwd()):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

全球

或者您可以使用 glob 模块根据文件格式仅列出一些文件:

Or you can list only some files, depending on the file pattern using the glob module:

import glob
for filename in glob.glob('*.txt'):
   with open(os.path.join(os.cwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

它不必是当前目录,您可以在所需的任何路径中列出它们:

It doesn't have to be the current directory you can list them in any path you want:

path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

管道或者甚至可以使用通过 fileinput

PipeOr you can even use the pipe as you specified using fileinput

import fileinput
for line in fileinput.input():
    # do your stuff

然后将其用于管道:

ls -1 | python parse.py

这篇关于如何打开文件夹中的每个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:15