写入文件“for line in File”(Python)

2024-06-28 19:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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()

这是错误代码: 对于文件中的行: 不支持操作:不可读


Tags: thetextnametxtinputopenfileenter
1条回答
网友
1楼 · 发布于 2024-06-28 19:40:33

假设您正在将lastNamehourWage和{}写入文本文件,下面是操作方法:

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()

输出:

^{pr2}$

要添加任意数量的输入,请添加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()

输出:

^{4}$

相关问题 更多 >