Python 分配增量文件名
我需要在文件中搜索一些字符串,并将其中的内容复制到一个单独的文件中 例如,“Hello”在一个文件中重复多次。我想将这些后续“Hello”之间的文本复制到一个文件中。每次“Hello”重复后面的文本时,它都需要转到一个新文件 请确认我在下面的脚本中使用的逻辑是否正确,以及“if”循环中的缩进错误Python 分配增量文件名,python,Python,我需要在文件中搜索一些字符串,并将其中的内容复制到一个单独的文件中 例如,“Hello”在一个文件中重复多次。我想将这些后续“Hello”之间的文本复制到一个文件中。每次“Hello”重复后面的文本时,它都需要转到一个新文件 请确认我在下面的脚本中使用的逻辑是否正确,以及“if”循环中的缩进错误 import re text_file = "Hello.txt" search1 = "Hello" outfile = "charlie" write1 = False x = 0 with o
import re
text_file = "Hello.txt"
search1 = "Hello"
outfile = "charlie"
write1 = False
x = 0
with open(text_file , "r") as infile:
fi = infile.readlines()
with open("outfile%s" % x, "w") as fo:
fo.write("============================================ \n")
for line in fi:
if search1 in line:
write1 = True
x +=1
fo.write(line)
elif write1:
fo.write(line)
试试这个
text_file = 'Hello.txt'
search_key = 'Hello'
out_file = 'charlie_%d.txt'
current_file = None
occurrence = 0
with open(text_file, 'r') as input_file:
try:
for src_line in input_file:
if search_key in src_line:
# searched text is found, writing to file
occurrence += 1
if current_file:
current_file.close()
current_file = open(out_file % occurrence, 'w')
current_file.write("============================================ \n")
current_file.write(src_line)
elif current_file:
# no searched text, write line to already open file
current_file.write(src_line)
finally:
if current_file:
current_file.close()
我在上面试过了,但是在“If”循环之后,它仍然给了我缩进错误。我多次重新格式化脚本,但此错误始终存在+=1^TabError:缩进中制表符和空格的使用不一致我正在使用Pycharm。。。。。我只是试着复制和粘贴你粘贴的确切文本,它不知怎么起作用了(我仍然不知道上面粘贴的代码中的错误是什么)。。。。但我仍然无法实现我想要的。使用open(text_file,'r')作为输入_file:for src_line in input_file:if search_key in src_line:#找到搜索到的文本,在open(out_file%引用,'w')的情况下写入文件引用+=1作为输出文件:输出文件.write(“=====================================\n”)输出文件.write(src_行)elif write1:fo.write(src_行)print(“hello”)使用此代码,它只打印找到匹配文本的行,而不转到下一个“elif”打印其他文本