0

Is there any way in python to write a string to a text file in your directory without needing the text file to exist first?

I know you can write a text file like this:

a='a'
file1=open('sample.txt','a')
file1=write(a)
file1.close()

but I think this method requires the text file sample.txt to exist already in the working directory. I am wondering if I can write the 'a' to a file without the sample.txt needing to be a pre-existing file.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
MathStudent
  • 129
  • 11
  • 1
    Use `a+` so that if the file exists, it appends and if not, creates. – Chris Jun 30 '20 at 05:05
  • Do you mean a+ in the second line(the open command), cause that just gives the error that no such file exists in the directory. – MathStudent Jun 30 '20 at 05:08
  • `file1 = open("sample.txt", "a+")` gives an error? – Chris Jun 30 '20 at 05:09
  • The question heading is misleading, it says how to write text in a file without opening it. In description you wrote how to write text in a file which may or may not exist. I suggest to make your question little clear – anuragal Jun 30 '20 at 05:11
  • Sorry, that works. Something is going wrong in the other code that I am trying to apply this to, but your example works – MathStudent Jun 30 '20 at 05:15
  • If you want to put that as an answer then I will mark it as correct – MathStudent Jun 30 '20 at 05:15
  • Does this answer your question? [Writing to a new file if it doesn't exist, and appending to a file if it does](https://stackoverflow.com/questions/20432912/writing-to-a-new-file-if-it-doesnt-exist-and-appending-to-a-file-if-it-does) – Gino Mempin May 19 '22 at 14:38

0 Answers0