从文本文件中读取并将数据分配给新变量

时间:2013-08-06 10:50:29

标签: file variables python-3.x

Python 3程序允许人们从员工姓名列表中进行选择。 文本文件中的数据如下所示:('larry',3,100) (作为人名,工作周和付款)

我需要一种方法将文本文件的每个部分分配给一个新变量, 这样用户就可以输入新的周数,程序会计算新的付款。

以下是我的代码,并试图搞清楚。

import os
choices = [f for f in os.listdir(os.curdir) if f.endswith(".txt")]
print (choices)
emp_choice = input("choose an employee:")

file = open(emp_choice + ".txt")

data = file.readlines()
name = data[0]
weeks_worked = data[1]
weekly_payment= data[2]

new_weeks = int(input ("Enter new number of weeks"))
new_payment = new_weeks * weekly_payment
print (name + "will now be paid" + str(new_payment))

1 个答案:

答案 0 :(得分:0)

目前,您要将文件的前三行分配给nameweeks_workedweekly_payment。但你想要的(我认为)是将一行格式化为('larry', 3, 100)(每个文件只有一行吗?)。

所以你可能想要代码:

from re import compile

# your code to choose file

line_format = compile(r"\s*\(\s*'([^']*)'\s*,\s*(\d+)\s*,\s*(\d+)\s*\)")
file = open(emp_choice + ".txt")
line = file.readline()   # read the first line only
match = line_format.match(line)
if match:
    name, weeks_worked, weekly_payment = match.groups()
else:
    raise Exception('Could not match %s' % line)

# your code to update information

正则表达式看起来很复杂,但实际上非常简单:

\(...\)  matches the parentheses in the line
\s*      matches optional spaces (it's not clear to me if you have spaces or not
         in various places between words, so this matches just in case)
\d+      matches a number (1 or more digits)
[^']*    matches anything except a quote (so matches the name)
(...)    (without the \ backslashes) indicates a group that you want to read 
         afterwards by calling .groups()

这些内容是根据http://docs.python.org/2/library/re.html

中描述的更简单的部分(如*+以及\d)构建的

如果你想为很多行重复这个,你可能想要这样的东西:

name, weeks_worked, weekly_payment = [], [], []
for line in file.readlines():
    match = line_format.match(line)
    if match:
        name.append(match.group(1))
        weeks_worked.append(match.group(2))
        weekly_payment.append(match.group(3))
    else:
        raise ...