根据if语句将数据附加到文本文件

时间:2013-09-21 14:59:47

标签: python regex python-2.7 append match

我正在尝试自动更新新的课程详细信息。

# Example variables
completed = Yes
class = 13A
time = 11:00

if completed:
    # Check data class and time variables against text file and if they don't exist then add them, if they do exist do nothing.

我的文字文件如下:

13A
11:00
Top Students: Joe Smith, Tom Clarke, Jenna Sole
Top 3 
Attendance: 98.5%
Class Score: 54
Yes

13B
11:10
Top Students: Anni Moy, Jessica Longate, Phillip Tome
T3 
Attendance: 98.5%
Class Score: 54
Yes

14A
11:10
Top Students: John Doe, John Smith, Sam Ben
T2 
Attendance: 98.5%
Class Score: 54
Yes

有没有人知道如何做到这一点,如果有人能提供帮助,我将非常感谢。

1 个答案:

答案 0 :(得分:2)

这是解析文本文件并将其转储到变量中的代码。 下面的代码说明了如何使用正则表达式解析文本文件。

import re

fp = open('class_data.txt')
lines = fp.read(-1)
fp.close()

records = re.split('\n\s*\n', lines) #Split all the records
#print len(records)
for record in records:
    data =  record.split('\n')
    classid, classtime, top_students = data[0], data[1], re.split('^[A-Za-z ]*:', data[2])[1].split(',')
    attendance, score, completed = re.split('^[A-Za-z ]*:', data[4])[1], re.split('^[A-Za-z ]*:', data[5])[1], data[6]
    print classid, classtime, top_students, len(top_students), attendance, score, completed 

打印声明输出

13A 11:00 [' Joe Smith', ' Tom Clarke', ' Jenna Sole'] 3  98.5%  54 Yes
13B 11:10 [' Anni Moy', ' Jessica Longate', ' Phillip Tome'] 3  98.5%  54 Yes
14A 11:10 [' John Doe', ' John Smith', ' Sam Ben'] 3  98.5%  54 Yes

既然您已将文本文件转换为变量,我们现在可以添加代码以检查类是否已完成以及文件是否已包含在文件中,否则添加它

import re

fp = open('class_data.txt')
lines = fp.read(-1)
fp.close()

completed = Yes
class = 13A
time = 11:00  
isClassRecordFound = False

records = re.split('\n\s*\n', lines) #Split all the records
#print len(records)
for record in records:
    data =  record.split('\n')
    classid, classtime, top_students = data[0], data[1], re.split('^[A-Za-z ]*:', data[2])[1].split(',')
    attendance, score, completed = re.split('^[A-Za-z ]*:', data[4])[1], re.split('^[A-Za-z ]*:', data[5])[1], data[6]
    print classid, classtime, top_students, len(top_students), attendance, score, completed 
    if (completed):
        if (classid == class) and (time == classtime):
             isClassRecordFound = True
             break;
if not isClassRecordFound:
    with open("class_data.txt", "a") as myfile:
        myfile.write(class + '\n' + time)