Python I / O信息未写入.txt文件

时间:2017-11-18 18:03:49

标签: python list file-io

所以,我试图从循环中将值写入每个列表...将小时乘以20,然后写出文件“workers.txt”。

该文件由脚本创建,但不会向其写入任何数据。我在我的智慧结束,这是相当普遍的。

with open('workers.txt', 'a') as filet:
    emp_num = [] #i am trying to write data 3 times to these lists
    emp_name = []
    hours = []
    pay = [0]

i = 0
take = 0
for i in range(3):
    emp_num.append(input('Employee ID: '))
    emp_name.append(input('Employee Name: '))
    hours.append(float(input('Hours: ')))
    pay.append(float(input(hours * 20)))
    i += 1

print(emp_num)
print(emp_name)
print(hours)
print(pay)

filet.close()

3 个答案:

答案 0 :(得分:1)

with语句中创建空列表不会将它们映射到文件。您仍然需要实际拨打filet.write

def make_employee():
    num = input("Employee ID: ")
    name = input("Employee name: ")
    hours = input("Hours: ")
    pay = float(hours) * 20
    return (num, name, hours, pay)


with open('workers.txt', 'a') as filet:
    for i in range(10):  # E.g., 10 employees
        num, name, hours, pay = make_employee()
        filet.write("{} {} {} {}\n".format(num, name, hours, pay))

答案 1 :(得分:1)

默认情况下,print函数会写入sys.stdout。如果您希望它写入您打开的文件,则应使用file关键字参数。

with open('workers.txt', 'a') as fout:
    emp_num = []
    emp_name = []
    hours = []
    pay = []

    # add 3 employees (user input -> lists)
    for i in range(3):
        emp_num.append(input('Employee ID: '))
        emp_name.append(input('Employee Name: '))
        hours.append(float(input('Hours: ')))
        pay.append(float(input(hours * 20)))

    # print lists' content to the file we opened
    print(emp_num, file=fout)
    print(emp_name, file=fout)
    print(hours, file=fout)
    print(pay, file=fout)

另请注意,上下文管理器将在退出时关闭文件 - 这就是为什么所有与文件相关的操作都必须在with块内。

答案 2 :(得分:1)

some_list = list()
with open('workers.txt') as filet:  # it is context manager, no need to close file manually
    for line in filet:  # read file line by line, saves operative memory
        some_list.append(line.strip())  # delete line wrapping

print(some_list)