I want to use argv to create a file using the command line (example >>> python thisscript.py nonexistent.txt ) then write to it from within my code. I've used the open(nonexistent, 'w').write() command but it seems I can only open and write to files that already exist. Am I missing something?
This is my code. It works as long as the file I'm trying to write to already exists
from sys import argv
script, letter_file = argv
string_let='abcdefghijklmnopqrstuvwxyz'
list_of_letters = list(string_let)
f = open(letter_file)
wf = open(letter_file, 'w')
def write_func():
for j in range(26):
for i in list_of_letters:
wf.write(i)
write_func()
wf.close()
raw_input('Press <ENTER> to read contents of %r' % letter_file)
output = f.read()
print output
But when the file does not aleady exist this is what I get returned to me in the terminal
[admin@horriblehost-mydomain ~]$ python alphabetloop.py nonexistent.txt
Traceback (most recent call last):
File "alphabetloop.py", line 14, in <module>
f = open(letter_file)
IOError: [Errno 2] No such file or directory: 'nonexistent.txt'
[admin@horriblehost-mydomain ~]$
open(filename, 'w')
is not only for existing files. If the file doesn't exist, it will create it:
$ ls mynewfile.txt
ls: mynewfile.txt: No such file or directory
$ python
>>> with open("mynewfile.txt", "w") as f:
... f.write("Foo Bar!")
...
>>> exit()
$ cat mynewfile.txt
Foo Bar!
Note that 'w'
will always wipe out the existing contents of the file. If you want to append to the end of an existing file or create the file if it doesn't exist, use 'a'
(i.e., open("mynewfile.txt", "a")
)