繁体   English   中英

如何遍历文本文件的行?

[英]How do I iterate over the lines of a text file?

我需要从文本文件中提取行,并将其用作python函数中的变量。

def call(file):
        with open(file) as infile, open('output.txt', 'w') as outfile:
            do stuff in a for loop

file是变量名,我计划有一个文本文件,其中包含文本文件名列表,如下所示:

hello.txt
world.txt
python.txt

我可以使用单个文件名调用该函数:

call(hello.txt)

但是我有一长串需要检查的文件。 在每个文件名调用一次函数时,如何逐行读取包含文件名的文件?

“在对每个文件名调用一次函数时,如何逐行读取包含文件名的文件?” ...您刚才解释了该怎么做。 假设您的文本文件包含其他文件名是"listoffiles.txt"

with open('listoffiles.txt') as fp:
    for line in fp:
        filename = line.strip()
        if filename:
            call(filename)

请注意,由于call会不断覆盖output.txt您可能还会遇到其他问题。

当然,根据其他设计目标,您可以在打开的文件对象而不是文件名上进行call工作。 这使该函数更通用,并且在其他情况下(例如,使用其他类似文件的对象,如StringIO可能有用。

def call(output, filename):
   with open(filename) as infile:
       # do some stuff directly with file

with open('output.txt', 'w') as output:
    with open('listoffiles.txt') as fp:
        for line in fp:
            filename = line.strip()
            if filename:
                call(output, filename)

在以下示例中,我将文本文件字符串分配给任意变量,然后消除“ .txt”,以便遵守变量名约定,然后将x的字符串值分配给数字2

x='hello.txt' 
x = x.replace(".txt","")  
exec("%s = %d" % (x,2))
print(str(x) + ' is equal to: ' + str(hello))

如果您尝试该代码,则应该得到

hello is equal to: 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM