I\'m experimenting with file I/O. I have a small practice program that creates a text file when run. I packaged it with pyinstaller so that double clicking on the exe creates a
Yes, you can do it with sys.argv
. Check out this link: http://docs.python.org/library/sys.html#sys.argv. But remember not to forget import sys
, and then you can use it.
import sys
# If there is an argument passed to your file
if len(sys.argv) > 1:
# argv[1] has your filename
filename = sys.argv[1]
print (filename)
# Output...
# new-host:~ yanwchan$ python3.2 test.py text.txt
# text.txt
argv[0]
has test.py
argv[1]
has text.txt
Edit: However, I do some more research on this topic and found out this: https://stackoverflow.com/a/4188500/1276534
As katrielalex points out, maybe you can look into argparse as well.? It provides a lot more functionality as well as safety check. Interesting information.
And here is a great tutorial: http://www.doughellmann.com/PyMOTW/argparse/