帮助使用python3中的文件

2024-09-28 03:20:28 发布

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

我目前正在学习python脚本的入门课程,需要帮助。给出了以下变量

The file name -> P = test.txt
firstname -> F = 'Ruthy'
lastname -> L = 'Anderson'
new birthday-> B = 00000000

目标是在文件中搜索给定的名字和姓氏,然后用“B”变量替换当前的生日。我们被告知每条记录的固定长度是40。你知道吗

下面是测试.txt文件包含

亚当·斯密11111985西奥多·安德森03201990Monty饼干桶10181980亚当·斯密11111900Ruthy Anderson 06062010

这是我到目前为止的代码。你知道吗

file1 = open(P, 'r')
data = file1.read()
file1.close()
file2 = open(P, 'w')
recordLength = 40
start = 0
records = []

while((len(data) - start) >= recordLength):
 record = data[start:start + recordLength]
 records.append(record)
 start+= recordLength

for i in range(0, len(records)):
 if re.seatch(F, data) and re.search(L, data):
  data = re.sub('10101960', B, data)

file2.write(data)
file2.close()

Tags: 文件retxt脚本closedatalenopen
1条回答
网友
1楼 · 发布于 2024-09-28 03:20:28

IIUC我的方法如下:

# P = 'test.txt'
# F = 'Ruthy'
# L = 'Anderson'
# B = '00000000'

with open(P, 'r+') as f:
    while True:
        rec = f.read(40)
        if rec:
            if rec.startswith(f'{F} {L}'):
                pos = f.tell()
                f.seek(pos-8)
                f.write(B)
                break
        else:
            break

相关问题 更多 >

    热门问题