以特定方式更改文本文件中的文本
change text in text file in particular manner
我有一个文本文件,其中有些行名为
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)
我无法弄清楚我应该如何替换该行并使其符合我想要的原因。请不要删除或关闭问题,告诉我应该如何在评论中编辑问题,以便我可以更改它。
提前致谢
如果您的文件中有一行(作为字符串)并且它完全采用该格式,那么您可以在冒号分隔符上拆分字符串,然后 re-join 在适当的位置用逗号分隔。例如:
s = 'moves={123:abc:567:mno}'
t = s.split(':')
print(':'.join(t[:2])+','+':'.join(t[2:]))
输出:
moves={123:abc,567:mno}
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 帮助我即兴创作您的答案我已经找到问题的答案
我有一个文本文件,其中有些行名为
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)
我无法弄清楚我应该如何替换该行并使其符合我想要的原因。请不要删除或关闭问题,告诉我应该如何在评论中编辑问题,以便我可以更改它。 提前致谢
如果您的文件中有一行(作为字符串)并且它完全采用该格式,那么您可以在冒号分隔符上拆分字符串,然后 re-join 在适当的位置用逗号分隔。例如:
s = 'moves={123:abc:567:mno}'
t = s.split(':')
print(':'.join(t[:2])+','+':'.join(t[2:]))
输出:
moves={123:abc,567:mno}
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 帮助我即兴创作您的答案我已经找到问题的答案