-4

I want to know how to write a command that clears a text file of all of its text? So I already have a .txt file with some text in it and everytime i execute the script it automaticly clears the .txt file of all its text. I am new to coding and do not know much.

JunJunXR
  • 11
  • 1
  • Oh ok, that was a quick reply let me try that! – JunJunXR Feb 09 '21 at 17:00
  • 1
    Welcome to Stack Overflow! Please take the [tour], and read [ask] and [what's on-topic here](/help/on-topic). Please note that [asking on Stack Overflow is not a substitute for doing your own research.](//meta.stackoverflow.com/a/261593/843953) You can find a ton of good resources on the internet, and possibly many questions on SO that deal with similar problems. – Pranav Hosangadi Feb 09 '21 at 17:01

1 Answers1

1

When you open a file in write mode, it will overwrite its contents. There is no specific command that accomplishes what you're after, but this is a nifty hack:

Assuming you have this text file:

# foo.txt
foo
bar
baz

Opening it in w mode:

with open('foo.txt', 'w') as f:
    pass

Clears it:

$ cat foo.txt
$
TayTay
  • 6,882
  • 4
  • 44
  • 65