我对此很陌生,所以要保持温柔。因此,我正在尝试使用Python将一个以GA开头,以GB开头,从GC和GD开始的文本字符串从一个测试文件复制到另一个测试文件。因此,从文本文件Text1到文本2传输“ GA祝您有个美好的一天GB”和“ GC祝您有个美好的一天GD”。只有介于两者之间的内容,之后没有其他内容。请帮忙。谢谢
with open('Test1.txt') as infile, open('Test2.txt', 'w') as outfile:
copy = False
for line in infile:
if line.strip() == "GA":
copy = True
if copy:
outfile.write(line)
# move this AFTER the "if copy"
if line.strip() == "GB":
copy = False
答案 0 :(得分:0)
有一些测试字符串开头和结尾的函数:startswith
和endswith
。
因此归结为:
with open('Test1.txt') as infile, open('Test2.txt', 'w') as outfile:
for line in infile:
if line.startswith("GA") and line.endswith("GB") or line.startswith("GC") and line.endswith("GD"):
outfile.write(line)