Gilush
Gilush

Reputation: 81

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)

Upvotes: 0

Views: 949

Answers (3)

hack-tramp
hack-tramp

Reputation: 376

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

Upvotes: 2

GutZuFusss
GutZuFusss

Reputation: 140

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

Upvotes: 1

Kasra Hosseini
Kasra Hosseini

Reputation: 11

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

Upvotes: -1

Related Questions