Python打开文件并删除一行
我需要一个导入文件的程序 我的档案是:Python打开文件并删除一行,python,python-2.7,Python,Python 2.7,我需要一个导入文件的程序 我的档案是: 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 您可以按如下方式删除这些行: lines = [] wit
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
您可以按如下方式删除这些行:
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)
with open('myfile.txt') as file:
lines = [line for line_number, line in enumerate(file, start=1) if line_number not in [1, 6, 7]]
with open('myfile.txt', 'w') as file:
file.writelines(lines)
通过使用Python的with
命令,它可以确保文件在之后正确关闭。这种方法也可以转换为列表理解,如下所示:
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)
with open('myfile.txt') as file:
lines = [line for line_number, line in enumerate(file, start=1) if line_number not in [1, 6, 7]]
with open('myfile.txt', 'w') as file:
file.writelines(lines)
Python函数用于为返回的每个项返回索引。通过从
1
开始,它可以用来为正在读取的文件提供行号。很抱歉,这不是一个代码编写服务,您能否显示您的努力和任何错误如果您不导入文件来读取它,请打开它。更改标题。要回答此问题,请逐行阅读,删除文件并只写入所需的行(或将其写入新文件)。
# 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)