如何从我确定的文件中删除一定数量的字符? (Python)
我正在从一个txt文件中获取输入,并希望获取4个字符,然后在文件中将它们删除,然后取下4个字符并读取它们。如何从我确定的文件中删除一定数量的字符? (Python)
到目前为止,我有这样的:
test_file = open("Test.txt", "r+")
text_in_file = test_file.read()
index = 4
intake_piece = text_in_file[:index]
print(intake_piece)
所有我发现迄今是如何删除匹配字符串确切行,但我想删除字符使用索引号我选择一个点。
编辑:
我基本上是寻找在文件中读取,取前4个字符(它只是在一个随机顺序特定字符的txt文件),做了功能与那些和移动到接下来的4个,直到文件结束。
我已经成功地陪审团钻机的方式来实现类似的结果是什么我想在这里:
index_start = 0
index_finish = 4
count =1
test_file = open("dna.txt", "r")
read_file = test_file.read()
file_size = read_file.__len__()
print((file_size))
i = 1
index = 0
while(index < file_size):
print('the count is', count)
count += 1
index += 4
print('index: ',index)
intake = read_file[index_start:index_finish]
print(intake)
index_start += 4
index_finish +=4
text_file_output = open("Output%i.txt"%i,'w')
i += 1
text_file_output.write(intake)
text_file_output.close()
path = os.path.abspath("Output%i")
directory = os.path.dirname(path)
print(path)
test_file.close()
如果你正试图从文件中删除第4个字母,您可以使用正则表达式:
import re
characters = re.findall("[\w\W]", open('file.txt').read())
final_data = ''.join(characters[4:])
什么是正则表达式与此有关? –
@JonClements我对问题的理解是,OP想要删除第一个'n'字符,而不是行。使用're.findall',OP可以获得文件中所有字符的完整列表,然后使用列表切片技术删除第一个'n',或者建立在切片上。 – Ajax1234
好吧...所以我想这取决于我们是在说字符还是字节,然后我猜...我在想'open('file.txt')。read()[4:]' –
它总是_first 4_? –
你真的想从文件中删除它们,或者只是忽略它们吗? –
你是在整个文件中递归地执行它还是只关心前8个字符? – 0TTT0