Python 如何读写多个文件?

Python 如何读写多个文件?,python,Python,我想为此编写一个程序:在一个文件夹中,我有n个文件;首先读取一个文件并执行一些操作,然后将结果存储在单独的文件中。然后读取第二个文件,再次执行操作并将结果保存在新的第二个文件中。对n个文件执行相同的步骤。程序逐个读取所有文件,并分别存储每个文件的结果。请举例说明我如何做到这一点 import sys # argv is your commandline arguments, argv[0] is your program name, so skip it for n in sys.argv[1

我想为此编写一个程序:在一个文件夹中,我有n个文件;首先读取一个文件并执行一些操作,然后将结果存储在单独的文件中。然后读取第二个文件,再次执行操作并将结果保存在新的第二个文件中。对n个文件执行相同的步骤。程序逐个读取所有文件,并分别存储每个文件的结果。请举例说明我如何做到这一点

import sys

# argv is your commandline arguments, argv[0] is your program name, so skip it
for n in sys.argv[1:]:
    print(n) #print out the filename we are currently processing
    input = open(n, "r")
    output = open(n + ".out", "w")
    # do some processing
    input.close()
    output.close()
那么就这样称呼它:

./foo.py bar.txt baz.txt ./foo.py bar.txt baz.txt
您可能会发现该模块很有用。它正是为解决这个问题而设计的。

我想你错过的是如何检索该目录中的所有文件。 为此,请使用glob模块。 下面的示例将所有扩展名为*.txt的文件复制到扩展名为*.out的文件

import glob

list_of_files = glob.glob('./*.txt')           # create the list of file
for file_name in list_of_files:
  FI = open(file_name, 'r')
  FO = open(file_name.replace('txt', 'out'), 'w') 
  for line in FI:
    FO.write(line)

  FI.close()
  FO.close()

包含目录或文件名参数的特定列表的组合答案:

import sys
import os.path
import glob

def processFile(filename):
    fileHandle = open(filename, "r")
    for line in fileHandle:
        # do some processing
        pass
    fileHandle.close()

def outputResults(filename):
    output_filemask = "out"
    fileHandle = open("%s.%s" % (filename, output_filemask), "w")
    # do some processing
    fileHandle.write('processed\n')
    fileHandle.close()

def processFiles(args):
    input_filemask = "log"
    directory = args[1]
    if os.path.isdir(directory):
        print "processing a directory"
        list_of_files = glob.glob('%s/*.%s' % (directory, input_filemask))
    else:
        print "processing a list of files"
        list_of_files = sys.argv[1:]

    for file_name in list_of_files:
        print file_name
        processFile(file_name)
        outputResults(file_name)

if __name__ == '__main__':
    if (len(sys.argv) > 1):
        processFiles(sys.argv)
    else:
        print 'usage message'

我最近刚刚了解了os.walk()命令,它可能会对您有所帮助。 它允许您沿着目录树结构走下去

import os
OUTPUT_DIR = 'C:\\RESULTS'
for path, dirs, files in os.walk('.'):
    for file in files:
        read_f = open(os.join(path,file),'r')
        write_f = open(os.path.join(OUTPUT_DIR,file))

        # Do stuff

这个东西也可以读取多个文件,我的文件名是
fedaralist_1.txt
federalist_2.txt
,像这样,我有84个文件,直到
fedaralist_84.txt

我把文件读成f

对于文件名中的文件:
将open(f'federalist_{file}.txt',r')作为f:
f、 读()

我知道我在某处看到了这个带有open()的double
,但不记得在哪里。所以我建立了一个小例子,以防有人需要

""" A module to clean code(js, py, json or whatever) files saved as .txt files to 
be used in HTML code blocks.  """
from os import listdir
from os.path import abspath, dirname, splitext
from re import sub, MULTILINE

def cleanForHTML():
    """ This function will search a directory text files to be edited. """

    ## define some regex for our search and replace. We are looking for <, > and &
    ## To replaced with &ls;, &gt; and &amp;. We might want to replace proper whitespace
    ## chars to as well? (r'\t', '    ') and (f'\n', '<br>')
    search_ = ((r'(<)', '&lt;'), (r'(>)', '&gt;'), (r'(&)', '&amp;'))

    ## Read  and loop our file location. Our location is the same one that our python file is in.
    for loc in listdir(abspath(dirname(__file__))):

        ## Here we split our filename into it's parts ('fileName', '.txt')
        name = splitext(loc)

        if name[1] == '.txt':
            ## we found our .txt file so we can start file operations.
            with open(loc, 'r') as file_1, open(f'{name[0]}(fixed){name[1]}', 'w') as file_2:

                ## read our first file
                retFile = file_1.read()

                ## find and replace some text.
                for find_ in search_:
                    retFile = sub(find_[0], find_[1], retFile, 0, MULTILINE)

                ## finally we can write to our newly created text file.
                file_2.write(retFile)
一个模块,用于将保存为.txt文件的代码(js、py、json或其他文件)清理到 在HTML代码块中使用。”“” 从操作系统导入listdir 从os.path导入abspath、dirname、splitext 从重新导入子行,多行 def cleanForHTML(): “”“此功能将搜索要编辑的目录文本文件。”“” ##为我们的搜索和替换定义一些正则表达式。我们正在寻找和& ##要替换为&ls;,及;。我们可能需要替换适当的空格 ##查斯也去吗?(r'\t',''和(f'\n','
')) 搜索=((r'()',“”),(r'(&',&;')) ##读取并循环我们的文件位置。我们的位置与python文件所在的位置相同。 对于listdir中的loc(abspath(dirname(_文件__))): ##在这里,我们将文件名分成几个部分('filename','.txt') 名称=拆分文本(loc) 如果名称[1]='.txt': ##我们找到了.txt文件,因此可以开始文件操作。 用open(loc,'r')作为文件_1,open(f'{name[0]}(fixed){name[1]},'w')作为文件_2: ##阅读我们的第一个文件 retFile=file_1.read() ##查找并替换一些文本。 对于搜索中的查找: retFile=sub(查找[0],查找[1],retFile,0,多行) ##最后,我们可以写入新创建的文本文件。 文件2.写入(retFile)
可能吧。但同时,我自己也在学习Python,这似乎是一个很好的练习,可以提醒自己我没有把头撞到墙上。如果他不关心自己学习这个级别的东西,那么我还能和谁争论呢?最后,如果你考试不及格,你还是不及格;询问和回答家庭作业问题在网站的花名册中,但是为了询问者的利益,我希望我们首先要求他们提供迄今为止不起作用的代码。打印(n)以使其与python 3兼容。至少在2.4中仍然可以使用。对于一个参数来说,这可能有些过分,但我建议使用optparse模块进行命令行解析。处理诸如处理报价等难看的任务。本例中有一个小问题。如果我有一个名为“mytxtfile.txt”的文件,会发生什么?
""" A module to clean code(js, py, json or whatever) files saved as .txt files to 
be used in HTML code blocks.  """
from os import listdir
from os.path import abspath, dirname, splitext
from re import sub, MULTILINE

def cleanForHTML():
    """ This function will search a directory text files to be edited. """

    ## define some regex for our search and replace. We are looking for <, > and &
    ## To replaced with &ls;, &gt; and &amp;. We might want to replace proper whitespace
    ## chars to as well? (r'\t', '    ') and (f'\n', '<br>')
    search_ = ((r'(<)', '&lt;'), (r'(>)', '&gt;'), (r'(&)', '&amp;'))

    ## Read  and loop our file location. Our location is the same one that our python file is in.
    for loc in listdir(abspath(dirname(__file__))):

        ## Here we split our filename into it's parts ('fileName', '.txt')
        name = splitext(loc)

        if name[1] == '.txt':
            ## we found our .txt file so we can start file operations.
            with open(loc, 'r') as file_1, open(f'{name[0]}(fixed){name[1]}', 'w') as file_2:

                ## read our first file
                retFile = file_1.read()

                ## find and replace some text.
                for find_ in search_:
                    retFile = sub(find_[0], find_[1], retFile, 0, MULTILINE)

                ## finally we can write to our newly created text file.
                file_2.write(retFile)