【问题标题】:Remove first line from txt file using python3使用python3从txt文件中删除第一行
【发布时间】:2020-06-02 21:39:01
【问题描述】:

所以我有这段代码将 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


【解决方案1】:

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

【讨论】:

  • 效果很好!谢谢你的时间! (所有评论的人)
【解决方案2】:

在 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

【讨论】:

  • 从较早的解决方案中尝试过,但出现此错误: FileNotFoundError: [Errno 2] No such file or directory: 'c:/users/Gilush/Desktop/default.txt' 这是文件的时间不存在
  • 第一次打开时使用 'w+'。这使它有点hacky,但它是一个快速修复。或者,只需构建一些逻辑来检查文件是否存在,如果不存在,则创建它。可以使用f = open("myfile.txt", "x") 以干净的方式创建文件。不过,我会把剩下的交给你;)
  • 这给我留下了一个空文件。
【解决方案3】:

你可以这样做:

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

【讨论】:

  • 这很不习惯,从变量名到缺少上下文管理器。
猜你喜欢
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多