2015-09-28 69 views
1

我被要求爲一個課後俱樂部創建一個應該存儲在一個文件中的程序。我是python的新手,我的程序說「行」沒有定義。請幫忙!python中的基本文件處理

##Write a sign-up program for an after-school club; it should ask the user for the following details and store them in a file: 


##First Name 
##Last Name 
##Gender 
##Form 

print ("Sign up for an after school club here")

firstname = input ("What is your first name?") 
lastname = input ("What is your last name?") 
gender = input("What is your gender?") 
form = input("What is your form?") 

f = open("afterschoolclub.txt","w") 
lines = f.readlines() 
print(lines[0]) 
f.write("\n",firstname) 
f.write("\n",lastname) 
f.write("\n",gender) 
f.write("\n",form) 
f.close()` 

這個程序是現在問題解決了

+0

如果你給你的文件讀取權限會發生什麼:'f = open(「afterschoolclub.txt」,「wr」)'? –

回答

1

你一個試圖讀取仍可能爲空文件已打開寫....

開放使用(這會自動爲你關閉文件。

with open("afterschoolclub.txt","w")  as f: 

    f.write(firstname) 
    f.write(lastname) 
    f.write(gender) 
    f.write(form) 


with open("afterschoolclub.txt","r")  as f: 
    lines = f.readlines() 
    print(lines[0]) 
+0

謝謝。我的程序現在可以運行 – Alice