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

Remove first line from txt file using python3

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

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

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

在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 数组删除文件的第一行(是的,我知道它在技术上被称为列表...... ) 切片:

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

你可以这样做:

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

这会将您的 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()