![](/img/trans.png)
[英]“list index out of range” when try to output lines from a text file using 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.