簡體   English   中英

當我嘗試將文本行從輸入文件復制到輸出文件時,Python 輸出“無”,並在每一行進行編號

[英]Python outputs "None" when I try to copies the lines of text from the input file to the output file, numbering each line as it goes

我正在嘗試讀取fileA並將fileB的內容寫入fileA ,同時在 4 列中右對齊行號,但我一直得到“無”輸出。

fileA = input("Enter the filename 1: ")
fileB = input("Enter the filename 2: ")
lineNo = 0
f = open(fileA, 'r')
g = open(fileB, 'w')
for line in f:
    lineNo += 1
    h = print(lineNo,">", line)
    j = str(h).rjust(4, " ")
g.write(str(j))

有一些錯誤,但正如所指出的,print 語句導致了最大的問題。 這是一個調試版本:

fileA = input("Enter the filename 1: ")    
fileB = input("Enter the filename 2: ")
lineNo = 0
f = open(fileA, 'r')
g = open(fileB, 'w')
for line in f:
    lineNo += 1
    h = str(lineNo).rjust(4) + ">" + line
    g.write(h)

print可以使用file=g參數寫入文件以及控制台,但是您會發現print還會添加一個換行符,而line字符串中已經有一個換行符。 使用end=''來抑制多余的行號。

enumerate是一個很好的函數,用於對正在迭代的內容進行編號。 它默認從零開始編號,但添加start=1將從一開始編號。

使用with語句確保您的文件已關閉。 如果不關閉文件,在某些 IDE 中運行代碼時,它可能不會刷新到磁盤。

例子:

fileA = input("Enter the filename 1: ")
fileB = input("Enter the filename 2: ")
with open(fileA, 'r') as f, open(fileB, 'w') as g:
    for lineNo,line in enumerate(f, start=1):
        print(f"{lineNo:>4}> {line}", end='', file=g)

暫無
暫無

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

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