我有一個文本檔案,其中有一些名為
moves={123:abc:567:mno}
不,我想將其轉換為形式
moves={123:abc, 567:mno}
即我想替換: ,當':'在一個字串之后和一個數字之后,即我想讓它像python字典格式一樣我知道如何更改文本檔案中的特定行,例如
with open("images/filename.txt", 'r ', encoding='Latin1') as fp:
# read an store all lines into list
lines = fp.readlines()
# move file pointer to the beginning of a file
fp.seek(0)
# truncate the file
fp.truncate()
for line in lines:
if line.startswith('moves='):
do something()
fp.writelines(lines)
我無法弄清楚我應該如何替換該行并使其成為我想要的原因。請不要洗掉或關閉問題告訴我應該如何在評論中編輯問題,以便我可以更改它。提前致謝
uj5u.com熱心網友回復:
如果您的檔案中有一行(作為字串)并且它完全采用該格式,那么您可以在冒號分隔符上拆分字串,然后在適當的位置用逗號重新加入。例如:
s = 'moves={123:abc:567:mno}'
t = s.split(':')
print(':'.join(t[:2]) ',' ':'.join(t[2:]))
輸出:
moves={123:abc,567:mno}
uj5u.com熱心網友回復:
s = 'moves={123:abc:567:mno}'
t = s.split(':')
print(t[2:5])
# print(':'.join(t[:2]) ',' ':'.join(t[2:]))
output = ''
for i in range(int(len(t)/2)):
output = ':'.join(t[i*2:i*2 2]) ', '
output = output.removesuffix(', ')
print(output)
感謝@Lancelot du Lac 幫助我即興回答我的問題我得到了答案
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465549.html
