![](/img/trans.png)
[英]Im trying to do some code in python that reads a text file and picks out the 5 lines with the highest number and prints them
[英]Trying to python code that prints out a certain value to a txt file
代碼:
'def'/myName = input() \r
/myName = 'Albert' \r
text_file = open("C:\Output.txt", "w") \r
text_file.write("myName") \r
text_file.close()
我的意思是,這是我第一次用 python 為學校作業編碼,但它在第一個 \\r 之后一直給我這個“語法錯誤:行連續字符后的意外字符”。 有人可以解釋一下/幫我解決這個問題嗎?
-唐尼
myName = raw_input('type name: ')
with open("output.txt", "w") as textfile:
textfile.write(myName)
您的代碼表明您根本不熟悉 Python 的語法及其工作原理。 這是對您的錯誤的解釋(根據您的要求):
'def'/myName = input() \r
def不需要在它周圍加上撇號,而myName不需要正斜杠。 你不能在第一行設置一個函數來做某事 - 這是正確的語法:
def foo():
bar = input('carrot: ')
print(bar)
此外,您需要在做任何事情之前將輸入存儲在一個變量中; 輸入需要一個字符串。 您不需要在每一行后都回車。 在括號之后,您需要一個冒號。
/myName = 'Albert' \r
您不能將函數設置為等於字符串。
text_file = open("C:\Output.txt", "w") \r
text_file.write("myName") \r
myName是一個變量,而不是一個字符串,所以你不需要引號。
text_file.close()
這是工作代碼:
myName = input('Name: ') # ask for input, which will be stored in myName
text_file = open('C:\output.txt', 'w') # open the output file in write mode
text_file.write(myName) # write myName to the output file
我建議在進一步嘗試之前閱讀官方 Python 教程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.