簡體   English   中英

將 output 從打印寫入 python 中的文件

[英]write output from print to a file in python

我有一個讀取多個文本文件並打印最后一行的代碼。

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)

我想將打印重定向到 output txt 文件,以便我檢查句子。 txt 文件也有多行空格。 我想刪除所有空行並將文件的最后一行放入 output 文件。 當我嘗試寫入時,它只寫入最后一個讀取文件。 並非所有文件最后一行都被寫入。

有人可以幫忙嗎?

謝謝, 阿魯什

而不是僅僅打印,做這樣的事情:

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

或者你也可以 append 到文件!

我想你有兩個不同的問題。
下次使用堆棧溢出時,如果您有多個問題,請單獨發布。

問題 1

如何將 output 從print function 重定向到文件?
例如,考慮一個 hello world 程序:

 print("hello world")

我們如何在當前工作目錄中創建一個文件(命名為text_file.txt ),以及 output 對該文件的打印語句?

答案 1

將 output 從print function 寫入文件很簡單:

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

請注意, print function 接受一個名為“ file ”的特殊關鍵字參數
您必須編寫file=f才能將f作為輸入傳遞給print function。

問題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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM