2015-12-10 79 views
-5

我需要一個導入文件的程序。 我的文件是:Python打開文件並刪除一行

1 abc 
2 def 
3 ghi 
4 jkl 
5 mno 
6 pqr 
7 stu. 

我想刪除行1,6和7

㈣嘗試了以下要導入的文件:

f = open("myfile.txt","r") 
lines = f.readlines() 
f.close() 
f = open("myfile.txt","w") 
if line = 1: 
    f.write(line) 
f.close 
+5

對不起等都不是代碼編寫的服務,您可以顯示你的努力和任何錯誤 – EdChum

+0

你不導入文件讀它,你打開它。更改標題。 – tglaria

+2

要回答,你一行一行地閱讀,擦除文件並只寫你想要的行(或將它們寫入一個新文件)。 – tglaria

回答

2

你可以刪除這些行如下:

lines = [] 

with open('myfile.txt') as file: 
    for line_number, line in enumerate(file, start=1): 
     if line_number not in [1, 6, 7]: 
      lines.append(line) 

with open('myfile.txt', 'w') as file: 
    file.writelines(lines) 

通過使用Python的with命令,它確保噸之後他的文件被正確關閉。

0
# Open your file and read the lines into a list called input 
input = open('my_file.txt', 'r').readlines() 

#create a list of lines you want to skip 
lines_to_skip = [1, 6, 7] 

with open('my_new_file.txt', 'w') as output: 
    for i, line in enumerate(input): 
     # check to see if the line number is in the list. We add 1 because python counts from zero. 
     if i+1 not in lines_to_skip: 
      output.write(line) 
相關問題