I cant seem to figure out why I keep getting this buggy output.
Input file:
ff1
ff2
ff3
ff10
ff11
ff20
ff21
ff23
gb20
gb10
gh23
Output File:
FF01
FF02
FF03
FF010
FF011
FF020
FF021
FF023
GB020
GB010
GH开发者_Go百科023
Code:
import os
import sys
#directory is the directory we will work from
directory = "C:\\Users\\user\\Desktop"
os.chdir(directory)
renameWhat = ["ff", "gb", "gh"]
oldFile = open("New Text Document.txt")
buffer = oldFile.read()
for item in renameWhat:
for i in range(0, 50):
if i < 10:
buffer = buffer.replace(item + str(i), item.upper() + "0" + str(i))
else:
buffer = buffer.replace(item + str(i), item.upper() + str(i))
outFile = open("test.txt", "w")
outFile.write(buffer)
outFile.close()
oldFile.close()
What needs to happen:
I'm trying to replace ff to uppercase (done), then I need to add zero's to all numbers that are less than or equal to 9
. So I think that if i is less than 10
should be good enough; but it's not because it's adding zeroes to everything over 9. I have tried with len(str(i))
to make sure it's only of length one, but that still does not work; what am I missing?
The reason your original solution doesn't work is that it isn't checking that it's matching a whole line/word/number. So for instance after replacing ff1
with FF01
your buffer is now:
FF01
ff2
ff3
FF010
FF011
ff20
ff21
ff23
gb20
gb10
gh23
Here is a simple solution:
with open("New Text Document.txt") as oldFile:
with open("test.txt", "w") as outFile:
for line in oldFile:
start, end = line[:2], line[2:]
outfile.write(start.upper() + end.strip().zfill(2) + '\n')
If you only want to uppercase specific prefixes:
with open("New Text Document.txt") as oldFile:
with open("test.txt", "w") as outFile:
for line in oldFile:
start, end = line[:2], line[2:]
if start in renameWhat:
start = start.upper()
outfile.write(start + end.strip().zfill(2) + '\n')
Just use the zfill string method:
>>> str(1).zfill(2)
'01'
>>> str(10).zfill(2)
'10'
import re
a = """ff1
ff2
ff3
ff10
ff11
ff20
ff21
ff23
gb20
gb10
gh23
"""
regex = re.compile('([a-zA-Z]*)([0-9]*)\n')
b = ""
for i in regex.findall(a):
if i[0] in ['ff','gb','gh']:
b+=i[0].upper()
else:
b+=i[0]
if int(i[1]) < 10:
b+= "0"
b+= i[1]+"\n"
print b
Result:
FF01
FF02
FF03
FF10
FF11
FF20
FF21
FF23
GB20
GB10
GH23
精彩评论