2017-10-21 43 views
0

我正在從一個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() 
+0

它總是_first 4_? –

+0

你真的想從文件中刪除它們,或者只是忽略它們嗎? –

+0

你是在整個文件中遞歸地執行它還是隻關心前8個字符? – 0TTT0

回答

0

如果你正試圖從文件中刪除第4個字母,您可以使用正則表達式:

import re 
characters = re.findall("[\w\W]", open('file.txt').read()) 
final_data = ''.join(characters[4:]) 
+0

什麼是正則表達式與此有關? –

+0

@JonClements我對問題的理解是,OP想要刪除第一個'n'字符,而不是行。使用're.findall',OP可以獲得文件中所有字符的完整列表,然後使用列表切片技術刪除第一個'n',或者建立在切片上。 – Ajax1234

+0

好吧...所以我想這取決於我們是在說字符還是字節,然後我猜...我在想'open('file.txt')。read()[4:]' –

相關問題