使用python3从txt文件中删除第一行

时间:2020-06-02 21:39:01

标签: python python-3.x file-io

所以我有这段代码将ping结果写入txt文件,但是它跳过了第一行,这意味着该文件总是得到一个空的第一行。

如何删除它? 甚至更好,我如何直接打印到第一行?

file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
with open(file, 'w+') as output:
    sub.call(['ping', f'{host}'], stdout=output)

3 个答案:

答案 0 :(得分:2)

这会将ping输出到文本文件的顶部:

import io, subprocess

ping = subprocess.Popen(["ping", "-n", "3","127.0.0.1"], stdout=subprocess.PIPE)

with open('ping.txt', 'r+') as output:
   data = output.read()
   for line in ping.stdout.readlines():
      data += str(line.decode())
   ping.stdout.close()
   output.seek(0)
   output.write(data.lstrip())
   output.truncate()

答案 1 :(得分:1)

在Python3中,这是2个衬里:

some_string = 'this will be the new first line of the file\n'

with open(fr'c:/users/{os.getlogin()}/Desktop/default.txt', 'r') as old: data = old.read()
with open(fr'c:/users/{os.getlogin()}/Desktop/default.txt', 'w') as new: new.write(some_string + data)

要回答是否有任何可怜的小伙子绊倒这个线程的原始问题,以下是如何使用python数组删除文件的第一行(是的,我知道它在技术上称为list ...)切片:

filename = fr'c:/users/{os.getlogin()}/Desktop/default.txt'

# split file after every newline to get an array of strings
with open(filename, 'r') as old: data = old.read().splitlines(True)
# slice the array and save it back to our file
with open(filename, 'w') as new: new.writelines(data[1:])

有关列表切片的更多信息:https://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html

扩展列表切片:https://docs.python.org/2.3/whatsnew/section-slices.html

答案 2 :(得分:-1)

您可以这样做:

F=open("file.text")
R=F.readlines()
Length=len(R)
New_file=R[1:Length-1]
for i in New_file:
    F.writelines(i)
F.close()

还访问This