【问题标题】:Appending data to text file dependant on if statment [closed]根据 if 语句将数据附加到文本文件[关闭]
【发布时间】:2013-09-26 20:43:56
【问题描述】:

我正在尝试获取一个自动更新新课程详细信息的文本文件。

# 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

有谁知道如何做到这一点,如果有人能提供帮助,我将不胜感激。

【问题讨论】:

  • 您自己尝试过吗?你遇到了什么问题?
  • 是的,我自己确实尝试过一些东西,但我不确定/无法使用 split('/n/n') 进行正则表达式检查/匹配以将数据拆分为项目,然后匹配/检查每个项目。
  • 一种快速而肮脏的方式:completed = (class + '\n' + time) in file.read()
  • @Michael0x2a completed 不是 class + time 在文本文件中的每个“项目”中成功匹配的结果,而是 completed 是告诉代码的触发器对照文件检查timeclass
  • 啊。然后,使用不同的变量名并在if 语句中进行检查?

标签: python regex python-2.7 append match


【解决方案1】:

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

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)

【讨论】:

  • 嗯,与我的尝试相差甚远,难怪我的尝试失败了。这完美地工作。获得绿色勾号 + 点赞 :) 谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多