![](/img/trans.png)
[英]How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in python
[英]replace first character of each line in file python
我正在嘗試替換多個 txt 文件中的一些第一個字符並具有此代碼,但 output 是錯誤的:
for filename in glob.glob('./labels/**/*.txt', recursive=True):
with open(filename, 'r') as f:
original_lines = f.readlines()
with open(filename, 'w') as out:
for line in original_lines:
if line.startswith('0'):
line0 = line
out.write(line0)
if line.startswith('1'):
line1 = line
out.write(line1)
if line.startswith('2'):
line2 = line
out.write(line2)
if line.startswith('3'):
line3 = line
out.write(line3)
if line.startswith('5'):
line4 = '4' + line[1:]
out.write(line4)
if line.startswith('7'):
line5 = '5' + line[1:]
out.write(line5)
if line.startswith('9'):
line6 = '6' + line[1:]
out.write(line6)
if line.startswith('10'):
line7 = '7' + line[1:]
out.write(line7)
if line.startswith('11'):
line8 = '8' + line[1:]
out.write(line8)
if line.startswith('12'):
line9 = '9' + line[1:]
out.write(line9)
因此,如果我有這樣的文件:
0 0.2 0.4 0.8
12 0.1 0.1 0.25
7 0.66 0.80 0.91
我希望 output 是:
0 0.2 0.4 0.8
9 0.1 0.1 0.25
5 0.66 0.80 0.91
我認為您有一些切片問題,例如假設您的輸入是12 0.1 0.1 0.25
line[1:]
將是2 0.1 0.1 0.25
因為您的輸入是字符串。 你可以使用類似的東西:
line = '12 0.1 0.1 0.25'.split(' ') #convert your string to a list
temp = int(line[0]) #get first element and convert to integer to make comparisons easier
if temp < 3:
print(' '.join(line))
elif temp == 5:
line[0] = '4'
print(' '.join(line))
elif temp == 7:
line[0] = '5'
print(' '.join(line))
elif temp > 8:
line[0] =str(temp - 3)
print(' '.join(line))
#Output:
9 0.1 0.1 0.25
注意:最好使用elif
而不是if
在您的情況下,因為如果您的條件之一為真,則不會檢查條件的 rest。 更多信息在這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.