def file():
Username_file = open("Username_file.txt", "w")
Username_file.close()
Username_file = open ("Username_file.txt", "a")
Firstname = input("Firstname:")
Lastname = input("Lastname:")
fullname = (Firstname, Lastname)
Username_file.write(str(fullname))
Username_file.close()
def perd():
**Personaldetails_file = open("Personaldetails_file.txt", "w")
Personaldetails_file = open("Personaldetails_file.txt", "a")**
pd = input("are you a new user?")
if pd == "yes":
print ("add your details")
age = int(input("how old are you?"))
DOB = input("Date of birth:")
gender = input("Gender:")
weight = int(input("weight in kg:"))
height = int(input("height in cm:"))
Personaldetails = (age, DOB, gender, weight, height)
Personaldetails_file.write(str(Personaldetails))
Personaldetails_file.close()
def td():
choice = input("which trainning event would you like to access?\n1.swimming\n2.cycling\n3.running\nplease type in the number before the event of which you want to choose\n")
if choice == "1":
Swimming_file= open("Swimming_file.txt", "w")
totaldistance = input("what was the total distance you swam in meters?")
totaltime = input("how long did you swim for in minutes?")
speed = totaldistance/totaltime
print ("on average you where running at a speed of", speed, "mps\nyou can look at the tables to see how many calouries you have burnt")
total = (totaldistance, totaltime, speed)
Swimming_file.write(str(total))
Swimming_file.close()
elif choice == "3":
Running_file= open("Running_file.txt", "w")
totaldistanceR = int(input("what was the total distance you ran in KM?"))
totaltimeR = int(input("how long did you run for in minutes?"))
totaltimeR1 = 60/totaltimeR
speedR1 = totaldistanceR/totaltimeR1
calburn = (speedR1 * 95)/(60/totaltimeR1)
print ("The records have been saved")
print ("on average you where running at a speed of", speedR1, "KMph\nyou burnt",calburn," calouries")
totalR = (totaldistanceR, totaltimeR, speedR1, calburn)
Running_file.write(str(totalR))
Running_file.close()
elif choice == "2":
Cycling_file= open("Cycling_file.txt", "w")
**with open(Personaldetails_file) as f:
content = [x.strip('\n') for x in f.readlines()]**
age = lines[0]
weight = lines [3]
height = lines [4]
totaldistancec = int(input("what was the total distance you cycled in KM?"))
totaltimec = int(input("how long did you cycle for in minutes?"))
calburn1 = (13.75 * weight) + (5 * height) - (6.67 * age)
speedc = totaldistancec/totaltimec
print ("on average you where running at a speed of", speedc, "KMph\nyou burnt", calburn1, " calouries")
totalc = (totaldistancec, totaltimec, speedc)
Cycling_file.write(str(totalc))
Cycling_file.close()
Personaldetails_file.close()
这是我的大部分课程。 我需要打开一个我在python中创建但使用不同函数的文件。如何在另一个功能中再次打开文件? 其中大部分与我的问题无关。我需要帮助的部分是粗体。
答案 0 :(得分:1)
变化
with open(Personaldetails_file) as f:
到
with open("Personaldetails_file.txt") as f:
您声明了变量" Personaldetails_file"这是perd()函数中的第一次,因此它只能从该函数访问(变量范围是该函数)。
绕过它的另一种方法=在其他地方使用变量,将其声明在代码顶部的任何函数之外。