如何在python中读取和更新源数据文件

2024-09-30 04:36:41 发布

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

我需要在读取后通过替换生成的随机字符串中的field3和field4值来修改文件。我确实尝试了一些方法,但它会删除文件的所有内容。任何投入和想法都是非常受欢迎的,因为这是使这件事运行的需要。多谢各位

import random
def rstring(length=8):
    valid_letters = '1234567890'
    return ''.join((random.choice(valid_letters) for i in range(length)))

with open('testfile.txt' , 'r+') as basefile:
    for basecontent in basefile:
        bline = basecontent
        print ("Data in file: ", bline)
    
        field1 = list(basecontent.split()[1:2])
        field1 = int(field1)
        print ("field1: ", field1)

        field2 = list(basecontent.split()[2:3])
        field2 = int(field2)
        print ("field2: ", field2)

        field3 = list(basecontent.split()[3:4])
        field3 = int(field3)
        print ("field3: ", field3)
    
        field4 = list(basecontent.split()[4:5])
        field4 = int(field4)
        print ("field4: ", field4)

        tofield3 = rstring(3) #-- generated random string length 3
        print ("replace field3 with this-> ", tofield3)

        tofield4 = rstring(5) #-- generated random string length 5
        print ("replace field4 with this-> ", tofield4)        
        print()

示例文件数据:

testfile.txt         ->  testfile.txt (modified output)
abcdef 11 14 17 20       abcdef 11 14 050 62726 - field3 to field4 from rstring(3/5)
ghijkl 12 15 18 21       ghijkl 12 15 437 58292 - field3 to field4 from rstring(3/5)
mnopqr 13 16 19 22       mnopqr 13 16 308 44976 - field3 to field4 from rstring(3/5)

Tags: 文件inwithrandomlengthlistintsplit
1条回答
网友
1楼 · 发布于 2024-09-30 04:36:41

我相信这符合你的要求

def rstring(length=8):
    valid_letters = '1234567890'
    return ''.join((random.choice(valid_letters) for i in range(length)))

basefile = open('testfile.txt' , 'r')
outfile = open('newfile.txt', 'w')
for bline in basefile:
    fields = bline.split()
    fields[3] = rstring(3)
    fields[4] = rstring(5)
    print( ' '.join(fields), file=outfile )

相关问题 更多 >

    热门问题