【问题标题】:How to read and update a source data file in python如何在python中读取和更新源数据文件
【发布时间】:2021-09-03 15:57:21
【问题描述】:

读取后我需要修改一个文件,方法是从生成的随机字符串中替换 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)

【问题讨论】:

  • replace 的全部内容是什么?您的数据中没有括号或引号。但是请注意,您不能就地修改文本文件。您需要将整个文件复制到一个新文件中,只写入更改的行。
  • 看在上帝的份上,不要将同一行拆分 4 次!拆分一次,将拆分保存在列表中,然后使用列表。
  • 非常感谢。我还在学习如何编程。至于我的需求,我希望自己修改文件而不是创建另一个。

标签: python python-3.x csv file


【解决方案1】:

我相信这符合您的要求。

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 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2021-03-29
    • 2018-06-24
    • 2011-07-25
    • 1970-01-01
    • 2017-03-14
    相关资源
    最近更新 更多