3

I have been reviewing the tutorial for file management in Python 3 but it doesn't mention how to create a file if one doesn't exist. How can I do that?

1
  • 1
    Did you try to use " f = open('workfile', 'w') " and see if python create the file itself ? I know In some languages this is a normal behavior. Commented Apr 5, 2013 at 0:08

5 Answers 5

4

Just open the file in w mode, and it will be created it.

If you want to open an existing file if possible, but create a new file otherwise (and don't want to truncate an existing file), read the paragraph in your link that lists the modes. Or, for complete details, see the open reference docs. For example, if you want to append to the end instead of overwriting from the start, use a.

Sign up to request clarification or add additional context in comments.

Comments

2

Just open the file in write mode:

f = open('fileToWrite.txt', 'w')

Note that this will clobber an existing file. The safest approach is to use append mode:

f = open('fileToWrite.txt', 'a')

As mentioned in this answer, it's generally better to use a with statement to ensure that the file is closed when you have finished with it.

3 Comments

Right, but even if you use a with statement don't you have to do f.close() to close the file?
@Nathan2055: It's kind of the whole point of with that you don't need f.close() (or, for other types, lock.release(), etc.)
Thanks @jordanm for the edit. I usually do footnote links but I was rushed today.
2

A new file is only created in write or append modes.

open('file', 'w')

In shell:

$ ls
$ python -c 'open("file", "w")'
$ ls
file
$

Comments

2

Of course.

   with open('newfile.txt', 'w') as f:
        f.write('Text in a new file!')

Comments

1

There are two types of files you can make. a text and a binary. to make a text file just use file = open('(file name and location goes here).txt', 'w'). to make a binary file you first import pickle, then to put data (like lists numbers ect..) in them you will need to use 'wb' and pickle.dump(data, file_variable) to take out you will need to use 'rb' and pickle.load(file_variable) and give that a variable becuase that is how you refrence the data. Here is a exaple:

import pickle #bring in pickle
shoplistfile = 'shoplist.data'
shoplist = ['apple', 'peach', 'carrot', 'spice'] #create data
f = open(shoplistfile, 'wb') # the 'wb'
pickle.dump(shoplist, f) #put data in
f.close
del shoplist #delete data
f = open(shoplistfile, 'rb') #open data remember 'rb'
storedlist = pickle.load(f)
print (storedlist) #output

note that if such a file exists it will be writen over.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.