我有一個 python 程式,它將要求用戶輸入,直到輸入空行并將它們寫入帶有行號的檔案中。它還將處理例外情況,以防它無法寫入檔案。預期的輸出是:
輸入檔案名:yogi.txt
輸入文本行。通過輸入空行退出。
我認識一個你不認識的人
Yogi,Yogi
檔案 yogi.txt 已寫入。
之后,檔案 yogi.txt 出現在專案檔案夾中,內容如下:
1 我認識一個你不認識的人
2 瑜珈,瑜珈
如果打開輸出檔案失敗,應立即列印以下錯誤資訊:
寫入檔案 yogi.txt 不成功。
我寫了以下代碼:
def main():
f = input("Enter the name of the file: ")
print("Enter rows of text. Quit by entering an empty row.")
try:
file1 = open(f, "w")
# declaring a list to store the inputs
list = []
while (inp := input(" ")):
list.append(inp)
for element in list:
file1.write(element "\n")
except IOError:
print("Writing the file", f, "was not successful.")
Lines = file1.readlines()
count = 0
# Strips the newline character
for line in Lines:
count = 1
file1.write("{} {}".format(count, line.strip()))
if __name__ == "__main__":
main()
但它顯示一些錯誤為不受支持的操作..
uj5u.com熱心網友回復:
發布的代碼正在從處于寫入模式的檔案中讀取行,因此它在Lines = file1.readlines()陳述句中失敗,并且操作不受支持。寫入后關閉檔案并以讀取模式打開它以將內容回顯到控制臺。
此外,當您可以在輸入時將行直接寫入檔案時,是否有理由將輸入存盤在串列中。
以下修復輸入和輸出并洗掉臨時串列。
def main():
f = input("Enter the name of the file: ")
print("Enter rows of text. Quit by entering an empty row.")
try:
with open(f, "w") as fout:
count = 0
while inp := input('>> '):
count = 1
fout.write(f'{count} {inp}\n')
except IOError:
print(f"Writing the file {f} was not successful.")
with open(f, "r") as fin:
# Strip the newline character
for line in fin:
print(line.strip())
if __name__ == "__main__":
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/352724.html
