当我尝试在python IDLE中运行代码时,它给出了第一行的语法错误,不知道为什么。试图让代码写入实验室的文本文档
Rfile=open (r 'C:\\Users\\cgeeg\\Desktop\\New_folder\\receipt.txt' )
file.write('Name:' )
file.write('Total Stock:' )
file.write('Commission:')
file.write('Total amount:' )
file.write('Net worth in Year(s:')
file.close()
myreceipt=f.readline()
A=float(Rfile.readline())
B=float(Rfile.readline())
C=float(Rfile.readline())
D=float(Rfile.readline())
E=float(Rfile.readline())
P=A*B
CT=P*C/ 100
T=CT+P
Y=P*(1+D/100)**10
print('Price paid for the stock alone is', P)
print('The amount of commission is', CT)
print('Total amount paid is', T)
print('After '+ E + ' years, your shares will be worth:', Y)
opt=input('Would you like a receipt? Yes or No?')
if opt=='Yes':
file=open('receipt.txt','w')
else:
print("Have a nice day")
答案 0 :(得分:1)
r
之后应该没有空格:
r'C:\\Users\\cgeeg\\Desktop\\New_folder\\receipt.txt'
一旦你解决了这个问题,你就会遇到另一个问题:如果你使用r
,你就不需要加倍反斜杠了。相反,如果你加倍反斜杠,你就不需要r
。所以试试这个:
r'C:\Users\cgeeg\Desktop\New_folder\receipt.txt'
答案 1 :(得分:0)
以正确的语法开头:
r'...'
,则无需在\
之前屏蔽\\
,并且在r和' "a"
(追加)或"r+"
(读取+写入)或"w"
(删除+写入)。在此处阅读更多内容:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
# change to 'w' instead of "r+" if does not yet exists or
# should be recreated each time deleting its content.
with open (r'C:\Users\cgeeg\Desktop\New_folder\receipt.txt',"r+" ) as f:
f.write('Name:\n' )
f.write('Total Stock:\n' )
f.write('Commission:\n')
f.write('Total amount:\n' )
f.write("Net worth in Year's:\n")
#autocloses here。