- Do I need to manually create a file and name it?
You mean the user, should you use existing tools to create the file, and then go back to Python to work on it? No. Python has all the tools needed to create a file. As vks explained in their answer , you should open the file using mode , which will create the file if it does not exist. You have chosen the read ('r') mode, which (correctly) will throw an error if there is no file to read at the location you specified, which leads us to ...
- I suppose I should declare a path, but how to do it in Python?
If you do not (if you say, for example, "filename.txt"), Python will look in the current working directory. By default, this is the current shell working directory when invoking the Python interpreter. This is almost always true if some program has changed it, which is unusual. To specify the path, you can either copy it, as you do, with the file name:
open('/full/path/to/filename.txt')
or you can build it using os.path .
Example:
I created an empty directory and opened the Python interpreter in it.
>>> with open('test.txt'): pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: 'test.txt' >>> with open('test.txt', 'w'): pass ... >>>
As noted, the read mode (default) gives an error because there is no file. Recording mode creates a file for us in which there is nothing. Now we see the file in the directory, and opening with read mode works:
>>> os.listdir(os.getcwd()) ['test.txt'] >>> with open('test.txt'): pass ... >>>
Now I create a subdirectory called "subdir" and move the text file there. I did this on the command line, but could just as easily do this in Python:
>>> with open('test.txt'): pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: 'test.txt' >>> with open('subdir/test.txt'): pass ...
Now we must specify the relative path (at least) to open the file, as on the command line. Here I "hardcoded" it, but it can be just as easily "built up" using the os module:
>>> with open(os.path.join(os.getcwd(), 'subdir', 'test.txt')): pass
(This is one example of how this could be done as an example.)