簡體   English   中英

Python程序在讀取文本文件后打印一個空行

[英]Python program prints one blank line after reading a text file

我正在做一些簡單的python練習,其中目標是簡單地讀取文本文件然后打印它。 但我的程序會打印一個額外的空行。

文本文件是model.txt,它有3個文本行和1個空行,在這里顯示

First row
Second row
This is the third row

我的節目是

file1=open("model.txt","r")
while True:
    row=file1.readline()
    print(row[:-1])
    if row=="":
        break
file1.close()

現在想要的打印結果是:

First row
Second row
This is the third row

但是印刷后還有一個額外的空白行:

First row
Second row
This is the third row

有一種方法可以刪除那一個空白行,但我無法弄明白。

這是因為你的循環不會很快break 請改為讀取您的文件:

with open('model.txt', 'r') as file1:
  for line in file1.readlines():
      trimmed_line = line.rstrip()
      if trimmed_line: # Don't print blank lines
          print(trimmed_line)

with語句將處理自動關閉文件, rstrip()刪除句子末尾的\\n和空格。

默認情況下, print()會為每行打印添加LF,因此如果您的print(row[:-1])為空( row[:-1]為空字符串),那么您仍然會獲得該行為。 解決方法是更換

print(row[:-1])

val = row[:-1]
if val: 
    print(val)

所以不打印空值。

file = open("model.txt", "r") 
for line in file: 
   print(line, end='')

因為讀取了換行符,所以也可以打印帶行的打印,不需要行[: - 1]

'end'選項留在這里,因為我需要閱讀這個頁面,過濾掉一些python2的東西,然后嘗試理解它做了什么;) 如何打印沒有換行符或空格?

暫無
暫無

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

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