我需要一个导入文件的程序。 我的档案是:
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
答案 0 :(得分: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
命令,它确保文件在之后正确关闭。
答案 1 :(得分: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)