Python 如何完全删除文本文件的第一行?
我有一个输出文本文件的脚本(Mod_From_SCRSTXT.txt)。我需要删除该文件的第一行 我已尝试更改下面显示的Python 如何完全删除文本文件的第一行?,python,Python,我有一个输出文本文件的脚本(Mod_From_SCRSTXT.txt)。我需要删除该文件的第一行 我已尝试更改下面显示的find函数的最后一行。即使进行了更改,第一行仍然会打印在创建的新文件中 def find(子文件、填充文件、输出文件): 打开(填充)为a,打开(输出文件“a”)为b: 对于a中的行: 如果substr在一行中: b、 写入(第[1:]行) srcn\U path1=input(“输入路径。示例:U:\…\…\SRCNx\SCRS.TXT\n”+ “输入SRCS.TXT的路径
find
函数的最后一行。即使进行了更改,第一行仍然会打印在创建的新文件中
def find(子文件、填充文件、输出文件):
打开(填充)为a,打开(输出文件“a”)为b:
对于a中的行:
如果substr在一行中:
b、 写入(第[1:]行)
srcn\U path1=input(“输入路径。示例:U:\…\…\SRCNx\SCRS.TXT\n”+
“输入SRCS.TXT的路径:”)
打印()
scrNumber1=输入('输入SCR编号:')
打印()
def查找(子文件、填充文件、输出文件):
打开(填充)为a,打开(输出文件“a”)为b:
对于a中的行:
如果substr在一行中:
b、 写(行)#或(行+'\n')
#行动站:
查找(scrNumber1,srcn_path1,'Mod_From_SCRSTXT.txt')
实际结果:
VSOAU-0004 16999
VSOAU-0004
VSOAU-0004
VSOAU-0004
VSOAU-0004
预期结果:
VSOAU-0004
VSOAU-0004
VSOAU-0004
VSOAU-0004
您需要做一个小的调整: 您可以计算文件中的行数:
numberOfLines = 0
for line in file:
numberOfLines += 1
for line in range(1, linesInFile + 1):
或者,您可以通过许多不同的方法忽略第一行,这是一个简单的方法:
ignoredLine = 0
for line in file:
if not ignoredLine:
ignoredLine = 1
else:
#Do stuff with the other lines
你在分割线而不是文件为什么要重新发明轮子,而你可以简单地
sed-i1d file.txt
?
import pathlib
import os
import copy
import io
def delete_first_line(read_path):
try:
read_path = pathlib.Path(str(read_path))
write_path = str(copy.copy(read_path)) + ".temp"
while os.path.exists(write_path):
write_path = write_path + ".temp"
with open(read_path , mode = "r") as inf:
with open(write_path, mode="w") as outf:
it_inf = iter(inf)
next(it_inf) # discard first line
for line in it_inf:
print(line, file = outf)
os.remove(read_path)
os.rename(write_path, read_path)
except StopIteration:
with io.StringIO() as string_stream:
print(
"Cannot remove first line from an empty file",
read_path,
file = string_stream,
sep = "\n"
)
msg = string_stream.getvalue()
raise ValueError(msg)
except FileNotFoundError:
with io.StringIO() as string_stream:
print(
"Cannot remove first line from non-existant file",
read_path,
file = string_stream,
sep = "\n"
)
msg = string_stream.getvalue()
raise ValueError(msg)
finally:
pass
return