【问题标题】:write output from print to a file in python将 print 的输出写入 python 中的文件
【发布时间】:2021-01-01 13:58:38
【问题描述】:

我有一个读取多个文本文件并打印最后一行的代码。

from glob import glob
text_files = glob('C:/Input/*.txt')
for file_name in text_files:
       with open(file_name, 'r+') as f:
           lines = f.read().splitlines()
           last_line = lines[-3]
           print (last_line)

我想将打印重定向到输出 txt 文件,以便检查句子。 txt 文件也有多行空格。我想删除所有空行并将文件的最后一行放到输出文件中。当我尝试写入时,它只写入最后一个读取文件。并非所有文件最后一行都已写入。

有人可以帮忙吗?

谢谢, 奥鲁什

【问题讨论】:

  • lines[-3] 如何让您进入最后行?
  • 这能回答你的问题吗? Print string to text file
  • 所以您的问题是您不知道如何写入文件,而不是打印到终端,您想将其写入文件,对吧?
  • @ScottHunter 。输入文件有最后 3 行空间,所以我给了这样的空间。我不知道如何删除文本文件中的空格,因为我有超过 10000 个文本文件作为输入。
  • @Countour-Integral,没错。 Print 在终端中给了我一行,但是当我尝试写入时,它并没有在最后一行写入所有 10000 个文件。但只有最后读取的文件。

标签: python printing


【解决方案1】:

不要只是打印,而是执行以下操作:

print(last_line)
with open('output.txt', 'w') as fout:
    fout.write(last_line)

或者你也可以追加到文件中!

【讨论】:

    【解决方案2】:

    我认为您有两个不同的问题。
    下次使用堆栈溢出时,如果您有多个问题,请单独发布。

    问题 1

    如何将print 函数的输出重定向到文件?
    例如,考虑一个 hello world 程序:

    print("hello world")
    

    我们如何在当前工作目录中创建一个文件(命名为text_file.txt),并将打印语句输出到该文件?

    回答 1

    print 函数的输出写入文件很简单:

    with open ('test_file.txt', 'w') as out_file:
        print("hello world", file=out_file)    
    

    请注意,print 函数接受名为“file”的特殊关键字参数
    您必须编写 file=f 才能将 f 作为输入传递给 print 函数。

    问题 2

    如何从 s 文件中获取最后一个非空行?我有一个输入文件,它的末尾有很多换行符、回车符和空格字符。我们需要忽略空行,并检索包含至少一个非空白字符的文件的最后一个留置权。

    回答 2

    def get_last_line(file_stream):   
        for line in map(str, reversed(iter(file_stream))):
    
            # `strip()` removes all leading a trailing white-space characters
            # `strip()` removes `\n`, `\r`, `\t`, space chars, etc...
    
            line = line.strip()
            
            if len(line) > 0:
                return line
    
         # if the file contains nothing but blank lines
         # return the empty string
         return ""
    

    您可以像这样处理多个文件:

    file_names = ["input_1.txt", "input_2.txt", "input_3.txt"]
    
    with  open ('out_file.txt', 'w') as out_file:
        for file_name in file_names:
           with open(file_name, 'r') as read_file:
               last_line = get_last_line(read_file)
               print (last_line, file=out_file)
    

    【讨论】: