我需要在读取后通过替换生成的随机字符串中的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)
我相信这符合你的要求
相关问题 更多 >
编程相关推荐