简体   繁体   English

如何遍历文本文件的行?

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

I need to take lines from a text file and use them as variables in a python function. 我需要从文本文件中提取行,并将其用作python函数中的变量。

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

file is the variable name and I plan to have a text file containing a list of text file names like so: file是变量名,我计划有一个文本文件,其中包含文本文件名列表,如下所示:

hello.txt
world.txt
python.txt

I can call the function with a single file name fine: 我可以使用单个文件名调用该函数:

call(hello.txt)

But I have a long list of files I need to go through. 但是我有一长串需要检查的文件。 How can I read the file containing the file names line by line while calling the function once with each file name? 在每个文件名调用一次函数时,如何逐行读取包含文件名的文件?

"How can I read the file containing the file names line by line while calling the function once with each file name?" “在对每个文件名调用一次函数时,如何逐行读取包含文件名的文件?” ... you just explained what to do. ...您刚才解释了该怎么做。 Supposing your text file containing other filenames is "listoffiles.txt" , 假设您的文本文件包含其他文件名是"listoffiles.txt"

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

Note that because call keeps overwriting output.txt you may have other issues. 请注意,由于call会不断覆盖output.txt您可能还会遇到其他问题。

Depending on other design goals of course, you could have call work on an open file object instead of a file name. 当然,根据其他设计目标,您可以在打开的文件对象而不是文件名上进行call工作。 This makes the function more generic and potentially useful for other cases such as using other file-like objects such as StringIO . 这使该函数更通用,并且在其他情况下(例如,使用其他类似文件的对象,如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)

in the following example I assign a text file string to an arbitrary variable I then eliminate the '.txt' so as to adhere to variable name convention then I assign the string value of x to a number 2 在以下示例中,我将文本文件字符串分配给任意变量,然后消除“ .txt”,以便遵守变量名约定,然后将x的字符串值分配给数字2

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

if you try the code you should get 如果您尝试该代码,则应该得到

hello is equal to: 2

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

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