简体   繁体   中英

Remove first line from txt file using python3

So I have this code that writes the ping results to a txt file but its skipps the first line which means the file always gets an empty first line.

how can I remove it? or even better, how can i print directly to the first line?

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

This will output your ping to the top of a text file:

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

In Python3, that is a 2 liner:

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)

To answer the original question for any poor lads stumbling upon this thread, here is how you delete the first line of a file using python array (yes, I know it is technically called list...) slicing:

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

More info on list slicing: https://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html

Extended list slicing: https://docs.python.org/2.3/whatsnew/section-slices.html

You can do this:

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

Also visit This

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM