按顺序读写文件-Python

按顺序读写文件-Python,python,Python,很抱歉,python作为一种语言还很陌生 所以我有5个文件。item1.txt、item2.txt、item3.txt、item4.txt和item5.txt。 我试图调用目录,以便它选择第一个文件item1.txt并打印其内容,然后当我再次调用该函数item2.txt时,文件中的内容将被打印。。。然后是item3.txt,然后是item4.txt 顺序很重要,系统必须知道打印了什么文件,以便行中的下一个文件可以在第一个文件之后打印,例如,item1.txt的内容先打印,然后是item2.txt

很抱歉,python作为一种语言还很陌生

所以我有5个文件。item1.txt、item2.txt、item3.txt、item4.txt和item5.txt。 我试图调用目录,以便它选择第一个文件item1.txt并打印其内容,然后当我再次调用该函数item2.txt时,文件中的内容将被打印。。。然后是item3.txt,然后是item4.txt

顺序很重要,系统必须知道打印了什么文件,以便行中的下一个文件可以在第一个文件之后打印,例如,item1.txt的内容先打印,然后是item2.txt

正在尝试使用:

for infile in sorted(glob.glob('*.txt')):
    print "Current File Being Processed is: " + infile
但问题是需要添加目录,系统需要知道在打印之前打印了什么文件及其内容

抱歉,这让人困惑


感谢您的帮助。

这就是您要搜索的内容吗

import glob
path = "path/to/your/txt/files/"
for infile in sorted(glob.glob(path + '*.txt')):
    print("Current File Being Processed is: " + path + infile)

如果需要了解完整路径,可以使用os.path.join

例如,搜索当前目录中所有文件的脚本如下所示:

import os
import os.path
import re


# look for all files in current working directory, including subdirs
for (root, folders, files) in os.walk(os.getcwd()):    
    for file in files:
        fullpath = os.path.join(root, file)
        print(fullpath)
for infile in sorted(glob.glob('*.txt')):
    inpath = os.path.abspath(infile)
    print "Current File Being Processed is: " + inpath
    with open(inpath) as infileobj:
        contents = infileobj.read()
    print contents
希望这有帮助

但问题是需要添加目录

为此,请使用中的方法

您可以执行pwd=os.getcwd来获取当前工作目录,即glob'*.txt'正在搜索的同一目录,然后使用us os.path.joinpwd,infle。但是对于特殊情况,当您只有一个相对于当前目录的路径时,您可能需要的是os.path.abspath。因此:

系统需要知道在打印之前打印了什么文件及其内容

要获取文件的内容,必须先获取它,然后再从中获取,如下所示:

import os
import os.path
import re


# look for all files in current working directory, including subdirs
for (root, folders, files) in os.walk(os.getcwd()):    
    for file in files:
        fullpath = os.path.join(root, file)
        print(fullpath)
for infile in sorted(glob.glob('*.txt')):
    inpath = os.path.abspath(infile)
    print "Current File Being Processed is: " + inpath
    with open(inpath) as infileobj:
        contents = infileobj.read()
    print contents
通常,您并不想将整个文件读入一个大字符串,您只想对文件中的每一行做一些工作。为此,您可以使用For语句,就像处理排序后返回的字符串列表一样,将文件视为一组行:

for infile in sorted(glob.glob('*.txt')):
    inpath = os.path.abspath(infile)
    print "Current File Being Processed is: " + inpath
    with open(inpath) as infileobj:
        for line in infileobj:
            print line.rstrip('\n')
rstrip“\n”是因为每行都以换行结束,但print会添加自己的换行,并且您不希望在文件的每行之间都有一个空行


这样做的好处是,您不必将整个文件读入内存即可打印出来。如果你处理的是小文件,这没什么大不了的,但是处理大文件会有很大的不同。

可能不会。它正在相对路径path/to/your/txt中搜索文件名files*.txt,如果找到,它将打印路径/to/your/txt/filesfoo.txt。这正是您使用os.path而不是字符串函数的原因,因为不可能创建像您在这里创建的两个这样愚蠢的错误。@abarnert:这是一种类型,是的,os.path可能更好。编辑了我的答案。这就是我的观点:如果您使用的代码与我们一直使用的相同类型的简单打字错误会导致大的、有时甚至难以调试的问题,这一事实比您碰巧确保输入错误的事实要重要得多。显示os.path.join很好,但我认为添加os.walk会让一个喜欢glob的新手感到困惑。