Making files with python script
Looking for someone to help me figure out why this doesn't work.
from sys import argv
script,filename = argv
filename = input()
target.write("hello world this is a random text file.")
I also have tried adding in 'w' so that it opens it in write mode.
from sys import argv filename=input() target=open(filename,'w') #open it for writing, as opposed to reading. target.write('hello') target.close()
@TutorialDoctor I tried your script, it always tells me no matter what name I put in that it "isn't defined." Also is there any need for importing arguments?
@lukecov Are you using Python 2 or 3? There is an important difference with the
inputfunction between the two versions.
In Python 2, there are two functions for reading user input, called
raw_inputfunction gives back the text typed by the user, as you would expect. The
inputfunction executes the user input as Python code (similar to how the
>>>prompt works) and returns the result. Most likely you are using Python 2, which means the
inputfunction tries to run your filename as Python code. Because it's a single word, it looks like a variable name, and Python complains that the name isn't defined.
In Python 2, you should never, ever use the
inputfunction. Not only is it confusing to users (the user can't tell if
raw_inputis used), but it is also a security problem. The user can type any Python code in there, for example code that deletes everything in Pythonista's Documents folder. You're just asking for a file name, so
raw_inputis the function to use here.
Because of how bad and useless the Python 2
inputfunction is, it was removed in Python 3. Instead, Python 2's
raw_inputwas renamed to
inputin Python 3 (and there is no
raw_inputin Python 3). This means that under Python 3
inputis the correct way to ask for text from the user.
If you're unsure what Python version your program is running on, you can add this code at the top to print out the Python version info:
import sys print(sys.version)
To answer your other question - no, there is no need to import
argvin the script posted by @TutorialDoctor. I'm guessing they forgot to remove the import after modifying your original code. Of course you can also change your code to take the filename from
sys.argv, but in Pythonista this not as useful as on a normal system, because Pythonista has no shell. By default Pythonista passes no arguments when running a program, but if you want, you can long-press the run button to pass
sys.argvarguments to your program.
I think the key difference is the syntax
target = open(filename).
@dgelessus thanks that helps a lot, and makes a lot sense. I'll make sure to not use input() on version 2. Even though I was just making files to mess around with not for any real purpose. Thanks a lot for explaining it.