The fileinput
module has a convenient inplace
keyword argument.
from fileinput import input as fileinput
import glob
with fileinput(files=glob.iglob('path to folder/*.txt', recursive=True), inplace=True) as f:
for line in f:
fields = line.split('')
if fields[0] == '7':
line = ''.join(['5'] + fields[1:])
print(line, end='')
Perhaps try without inplace=True
until you have convinced yourself that this works correctly.
I have simply assumed your columns are tab-delimited; it should not be too hard to adapt this to space-delimited or to simply use a different delimiter like comma etc. (If your input is proper CSV, perhaps use Python's csv
module instead.)
I have also assumed that you only want to change 7
to 5
and not also e.g. 777
to 555
. If you wanted that, perhaps simply
# ...
fields[0] = fields[0].replace('7', '5')
line = ''.join(fields)
# ...
If your columns are separated by unpredictable amounts of whitespace but the field length does not change when you replace (like here, where you replace a single character with a single character), you can use
fields = line.split()
fields[0] = fields[0].replace('7', '5')
line = fields[0] + line[len(fields[0]):]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…