Reputation: 2373
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?
Upvotes: 3
Views: 5069
Reputation: 2166
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.
Upvotes: 1
Reputation: 46183
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.
Upvotes: 2
Reputation: 9584
Of course.
with open('newfile.txt', 'w') as f:
f.write('Text in a new file!')
Upvotes: 2
Reputation: 18282
A new file is only created in write or append modes.
open('file', 'w')
In shell:
$ ls
$ python -c 'open("file", "w")'
$ ls
file
$
Upvotes: 2
Reputation: 365647
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
.
Upvotes: 4