Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何打开文件夹中的每个文件_Python_File_Pipe_Stdout_Stdin - Fatal编程技术网

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

Python 如何打开文件夹中的每个文件,python,file,pipe,stdout,stdin,Python,File,Pipe,Stdout,Stdin,我有一个python脚本parse.py,它在脚本中打开一个文件,比如file1,然后做一些事情,可能会打印出字符总数 filename = 'file1' f = open(filename, 'r') content = f.read() print filename, len(content) 现在,我正在使用stdout将结果定向到我的输出文件-output python parse.py >> output 但是,我不想手动逐个文件地执行此操作,有没有办法自动处理每个文

我有一个python脚本parse.py,它在脚本中打开一个文件,比如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 
那么问题是如何从standardin读取文件名? 或者已经有一些内置函数可以轻松地完成ls和这类工作

谢谢

Os

您可以使用
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 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
它不必是当前目录,您可以在任何想要的路径中列出它们:

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

您应该尝试使用
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

您实际上可以使用来同时执行这两项操作:

  • 列出文件夹中的所有文件
  • 按文件类型、文件名等对文件进行排序
  • 下面是一个简单的例子:

    现在,您不仅列出了文件夹中的所有文件,还可以(可选)按起始名称、文件类型和其他文件进行排序。现在,反复浏览每个列表并完成您的工作。

    我正在寻找以下答案:

    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”或文件名的其他端

    下面的代码读取包含我们正在运行的脚本的目录中可用的任何文本文件。然后它打开每个文本文件并将文本行中的单词存储到列表中。存储单词后,我们逐行打印每个单词

    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('')
    
    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)
    

    这是否也可以自动打开和关闭文件?我很惊讶你没有使用
    与。。。作为…:
    语句。你能澄清一下吗?Charlie,glob.glob和os.listdir返回文件名。然后在循环中逐个打开这些文件。这将使用PyPerClip和PyAutoGui打开、打印、关闭目录中的每个PDF。希望其他人对此有所帮助。这是答案,因为您正在读取目录中的所有文件;D
    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)