![](/img/trans.png)
[英]Printing lines from file using python returning value in column, not by row
[英]Writing in a file and printing the input lines with a row number in python
我有一個 python 程序,它將要求用戶輸入,直到輸入空行並將它們寫入帶有行號的文件中。 如果它無法寫入文件,它還將處理異常情況。 預期的輸出是:
輸入文件名:yogi.txt
輸入文本行。 通過輸入空行退出。
我認識一個你不認識的人
瑜珈,瑜珈
文件 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()
但它顯示一些錯誤為不受支持的操作..
發布的代碼正在從處於寫入模式的文件中讀取行,因此它在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:
while inp := input(" "):
fout.write(inp + "\n")
except IOError:
print("Writing the file", f, "was not successful.")
with open(f, "r") as fin:
count = 0
# Strips the newline character
for line in fin:
count += 1
print("{} {}".format(count, line.strip()))
if __name__ == "__main__":
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.