大家好,我正在尝试按我想要的数字修改文件中的某些值。 问题是在最后一个附加值中插入了一个罕见的值。 我已经调试过了,但还是不明白如何解决。 我有一个包含从 1 到 10 的数字的文件,我想用我通过增加 +1 的函数传递的其他数字来更改它们。
import re
import glob
import os
filename="myfile.txt"
num = 9
def number():
global num
num += 1
return str(num)
with open(filename, "r") as f:
contents = f.read()
#1 to 10
contents = re.sub(r'^1', str(number()), contents, flags = re.MULTILINE)
contents = re.sub(r'^2', str(number()), contents, flags = re.MULTILINE)
contents = re.sub(r'^3', str(number()), contents, flags = re.MULTILINE)
contents = re.sub(r'^4', str(number()), contents, flags = re.MULTILINE)
contents = re.sub(r'^5', str(number()), contents, flags = re.MULTILINE)
contents = re.sub(r'^6', str(number()), contents, flags = re.MULTILINE)
contents = re.sub(r'^7', str(number()), contents, flags = re.MULTILINE)
contents = re.sub(r'^8', str(number()), contents, flags = re.MULTILINE)
contents = re.sub(r'^9', str(number()), contents, flags = re.MULTILINE)
contents = re.sub(r'^10', str(number()), contents, flags = re.MULTILINE)
with open(filename, "w") as f:
f.write(contents)
myfile.txt 这些是它包含的数字
1
2
3
4
5
6
7
8
9
10
myfile.txt 我期望的数字
10
11
12
13
14
15
16
17 号
18
19
myfile.txt 我得到的数字
19
11
12
13
14
15
16
17 号
18
190
以下通过简单的数值解描述了您想要的结果:
filename = "myfile.txt"
newfile = "newfile.txt"
NUMBER = 9
with open(filename, "r") as f:
content = f.readline()
number_list = [int(val) for val in content.split()]
for idx, num in enumerate(number_list):
number_list[idx] = str(num + NUMBER)
new_string = " ".join(number_list)
with open(newfile, "w") as f:
f.write(new_string)
我使用了不同的文件进行写入,但除此之外它应该创建您所描述的目标。
如果您的问题可以用数值方法解决,并且您知道应该尝试一下。它比字符串恶作剧要快得多。而且这样的话也比较容易理解。