用python3删除txt文件的第一行。

问题描述 投票:0回答:1

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

我怎样才能删除它呢?或者更好的是,我怎样才能直接打印到第一行?

file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
with open(file, 'w+') as output:
    sub.call(['ping', f'{host}'], stdout=output)
python python-3.x file-io file-manipulation
1个回答
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
投票

在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:])

更多关于list slicing的信息。https:/python-reference.readthedocs.ioenlatestdocsbracketsslicing.html。

扩展列表切片。https:/docs.python.org2.3whatsnewsection-slices.html。


-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()

还可以访问 这个

© www.soinside.com 2019 - 2024. All rights reserved.