How to create and open files through Python?

I have a very elementary question, but I tried to find the previous posts and can not find anything that could help. I am studying an input / output file in Python. All the tutorials I've seen so far seem to have skipped the step and just assumed that the file was already created, and just saying something like handleName = open('text.txt', 'r') , but that leaves me 2 unanswered questions:

  • Should I create a file manually and name it? I use a Mac, so I need to go to applications, open TextEdit, create and save a file, or can I do this with some command in IDLE?
  • I tried to manually create the file (as described above), but then when I tried to enter openfile = open('test_readline', 'r') , I got the error: IOError: [Errno 2] No such file or directory: 'abc'

As for the error, I suppose I should declare a path, but how to do it in Python?

+5
source share
4 answers
 openfile = open('test_readline', 'w') ^^ 

Opening in write mode will create the file if it does not already exist. Now you can write to it and close the file pointer, and it will be saved.

+4
source

To be able to read from any file, the file must exist. Right? Now look here, the I / O file has the syntax as shown below:

 fp = open('file_name', mode) # fp is a file object 

The second argument, for example, describes how to use the file. w mode will open any existing file (if it exists) with the name specified in the first argument. Otherwise, a new file with the same name is created. Also, if you are on Windows and want to open the file in binary mode, add b to mode. For instance. use wb to open a file for writing in binary mode. Note that if you try to open any existing file in w (write) mode, then the existing file with the same name will be deleted. If you want to write an existing file without deleting the old data, use a mode. It adds new data to the end of the previous one.

 fw = open('file_name','w') fa = open('file_name','a') # append mode 

To learn more, you can refer to the Python File I / O document. Hope this helps!

+2
source

Python automatically uses the default path.

 import os default_path = os.getcwd() ## Returns the default path new_path = "C:\\project\\" ## Path directory os.chdir(path) ## Changes the current directory 

Once you change the path, the files you write and read will be in C: \ project. If you try and read the project elsewhere, the program will fail.

os.chdir is how you declare or set the path in python.

+1
source
  • 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 ...

  1. 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 ... >>> # ^ No IOError because it exists now 

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.)

0
source

All Articles