f = input("Name the text file: ")
file = open(f+".txt", "w")
lastName = input("Enter the name: ")
hourWage = str(input("Enter the hourly wage: "))
hourWorked = str(input("Enter the worked hours: "))
for line in file:
file.close()
这是错误代码: 对于文件中的行: io.UnsupportedOperation:不可读
答案 0 :(得分:1)
假设您正在向文本文件写lastName
,hourWage
和hourWorked
,请按以下步骤操作:
fileName = str(input("Name the text file: "))
f = open(fileName + ".txt", "w")
lastName = input("Enter the name: ")
hourWage = str(input("Enter the hourly wage: "))
hourWorked = str(input("Enter the worked hours: "))
f.write(lastName + "\t" + hourWage + "\t" + hourWorked + "\n")
f.close()
输出:
mou@mou-lanister:~$ python ./test.py
Name the text file: Something
Enter the name: John Doe
Enter the hourly wage: 60
Enter the worked hours: 100
mou@mou-lanister:~$ cat Something.txt
John Doe 60 100
要添加任意数量的输入,请添加while
循环:
fileName = str(raw_input("Name of the file: "))
f = open(fileName + ".txt", "w")
while True:
lastName = input("Enter the name: ")
hourWage = str(input("Enter the hourly wage: "))
hourWorked = str(input("Enter the worked hours: "))
f.write(lastName + "\t" + hourWage + "\t" + hourWorked + "\n")
confirm = input("Do you want to continue(Y / N)?").lower()
n = ['no', 'n']
if confirm in n:
break
f.close()
输出:
mou@mou-lanister:~$ python ./something.py
Name of the file: data
Enter the name: Someone
Enter the hourly wage: 99
Enter the worked hours: 64728
Do you want to continue(Y / N)?y
Enter the name: Someone Else
Enter the hourly wage: 63
Enter the worked hours: 387495
Do you want to continue(Y / N)?YES
Enter the name: John Doe
Enter the hourly wage: 89
Enter the worked hours: 3441234
Do you want to continue(Y / N)?Y
Enter the name: John Conner
Enter the hourly wage: 64
Enter the worked hours: 2134
Do you want to continue(Y / N)?n
mou@mou-lanister:~$ cat data.txt
Someone 99 64728
Someone Else 63 387495
John Doe 89 3441234
John Conner 64 2134
mou@mou-lanister:~$