如何打开文件夹中的所有文件

210

我有一个名为parse.py的Python脚本,该脚本打开一个文件,比如file1,然后执行一些操作,可能会打印出字符总数。

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

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

python parse.py >> output

然而,我不想手动逐个文件完成此操作,是否有一种方法可以自动处理每个单独的文件?例如

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

那么问题来了,如何从标准输入中读取文件名呢?或者已经有一些内置函数可以轻松地执行ls和类似的操作吗?

谢谢!

8个回答

456

操作系统

您可以使用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

或者你可以使用 glob 模块根据文件模式列出某些文件:

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

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

import os, glob
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

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

然后您可以使用管道与其一起使用:

ls -1 | python parse.py

4
这会自动处理文件的打开和关闭吗?我很惊讶你没有使用“with ... as ...:”语句。你能澄清一下吗? - Charlie Parker
5
Charlie、glob.glob 和 os.listdir 返回文件名。然后在循环内逐个打开这些文件。 - David R

45

你应该尝试使用 os.walk

import os

yourpath = 'path'

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

32

我正在寻找这个答案:

import os,glob
folder_path = '/some/path/to/file'
for filename in glob.glob(os.path.join(folder_path, '*.htm')):
  with open(filename, 'r') as f:
    text = f.read()
    print (filename)
    print (len(text))

你可以选择以'.txt'或其他文件名结尾


这是答案,因为您正在读取目录中的所有文件;D - Khan

12

您实际上可以只使用 os 模块 来完成以下两个任务:

  1. 列出文件夹中的所有文件
  2. 按文件类型、文件名等对文件进行排序

这里有一个简单的示例:

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

现在你不仅列出了文件夹中的所有文件,而且还可以按起始名称、文件类型等进行排序(可选)。现在只需遍历每个列表并执行相应操作。

3
import pyautogui
import keyboard
import time
import os
import pyperclip

os.chdir("target directory")

# get the current directory
cwd=os.getcwd()

files=[]

for i in os.walk(cwd):
    for j in i[2]:
        files.append(os.path.abspath(j))

os.startfile("C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe")
time.sleep(1)


for i in files:
    print(i)
    pyperclip.copy(i)
    keyboard.press('ctrl')
    keyboard.press_and_release('o')
    keyboard.release('ctrl')
    time.sleep(1)

    keyboard.press('ctrl')
    keyboard.press_and_release('v')
    keyboard.release('ctrl')
    time.sleep(1)
    keyboard.press_and_release('enter')
    keyboard.press('ctrl')
    keyboard.press_and_release('p')
    keyboard.release('ctrl')
    keyboard.press_and_release('enter')
    time.sleep(3)
    keyboard.press('ctrl')
    keyboard.press_and_release('w')
    keyboard.release('ctrl')
    pyperclip.copy('')

1
使用PyPerClip和PyAutoGui打开、打印、关闭目录中的每个PDF文件。希望其他人会发现这很有用。 - RockwellS

1
如果您想打开目录中的文件并将它们附加到列表中,请执行以下操作:
mylist=[]
for filename in os.listdir('path/here/'):
with open(os.path.join('path/here/', filename), 'r') as f:
    mylist.append(f.read())

1
下面的代码会读取包含我们运行脚本的目录中所有可用的文本文件。然后它会打开每个文本文件,并将文本行的单词存储到一个列表中。存储单词后,我们逐行打印每个单词。
import os, fnmatch

listOfFiles = os.listdir('.')
pattern = "*.txt"
store = []
for entry in listOfFiles:
    if fnmatch.fnmatch(entry, pattern):
        _fileName = open(entry,"r")
        if _fileName.mode == "r":
            content = _fileName.read()
            contentList = content.split(" ")
            for i in contentList:
                if i != '\n' and i != "\r\n":
                    store.append(i)

for i in store:
    print(i)

0
你可以尝试另一种使用 os.walk 和 os.path.join 的方法,这与上面的选项有些不同:
for root, dirs, files in os.walk(EnterYourPath):
    for name in files:
        with open(os.path.join(root,name))as f:
            text = f.read()

文本变量包括目录中文件夹中的所有文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接