1

In Python 2.7, I am writing a line to a file using..

f.write('This is a test')

How can I delete this line? The text file will only ever have one line in it so could / should I delete the file and create a new one?

Or is there a way to delete the line i added?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

3 Answers3

1

You can delete the file and create a new one or truncate the existing file

# the original file
with open("test.txt", "w") as f:
    f.write("thing one")

# delete and create a new file - probably the most common solution
with open("test.txt", "w") as f:
    f.write("thing two")

    # truncate an existing file - useful for instance if a bit
    # of code as the file object but not file name
    f.seek(0)
    f.truncate()
    f.write("thing three")

# keep a backup - useful if others have the old file open
os.rename("test.txt", "test.txt.bak")
with open("test.txt", "w") as f:
    f.write("thing four")

# making live only after changes work - useful if your updates
# could fail
with open("test.txt.tmp", "w") as f:
    f.write("thing five")
os.rename('test.txt.tmp', 'test.txt')

Which is better? They all are... depending on other design goals.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

In Python, you can't delete text from files. Instead you can write to a file.

The write function effectively deletes whatever is in the file and saves the file with the string you pass as arguments.

Example

open_file=open("some file","w")
open_file.write("The line to write")

Now the file has the line "The line to write" as the contents.

Edit The write function more precisely writes over from where the cursor. When you open in w mode, the cursor is at the front of the file and writes over everything in the file.

Thanks bli for pointing that out.

Superman
  • 196
  • 1
  • 2
  • 8
  • More precisely, it is the combination of opening (in "w" mode) and writing. If you write in an already opened file, this will append text to whatever you wrote since the `open`. – bli Oct 30 '16 at 06:46
0

It is a best practice to always use with when you open a file to make sure that your file will always be closed even if you do not call close()

with open('your_file', 'w') as f:
    f.write('new content')
ettanany
  • 19,038
  • 9
  • 47
  • 63