What does open return in python

Python open() Method

The open() method opens the file (if possible) and returns the corresponding file object.

open() Syntax:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Parameters:

  1. file: The path name of the file to be opened or an integer file descriptor of the file to be wrapped.
  2. mode: (Optional) An access mode while opening a file. Default mode is ‘r’ for reading. See all the access modes.
  3. buffering: (Optional) Used for setting buffering policy. Defaults to -1. Pass 0 if specified mode is binary ‘b’,
  4. encoding: (Optional) The encoding format to encode or decode the file.
  5. errors: (Optional) String specifying how to handle encoding/decoding errors.
  6. newline: (Optional) Conrols how newlines mode works. It can be None, », ‘\n’, ‘\r’, and ‘\r\n’.
  7. Closefd: (Optional) If a filename is given, it must be True. If False, the file descriptor will be kept open when the file is close
  8. Opener: (Optional) A custom callable file opener.

Return type:

File Access Modes

The following table lists the file access modes parameter values.

Access Modes Description
r Opens a file for reading only.
rb Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w Opens a file for writing only.
wb Opens a file for writing only in binary format.
w+ Opens a file for both writing and reading.
wb+ Opens a file for both writing and reading in binary format.
a Opens a file for appending.
ab Opens a file for appending in binary format.
a+ Opens a file for both appending and reading.
ab+ Opens a file for both appending and reading in binary format.
Читайте также:  Алгоритм евклида реализация python

The following example opens a file from the current directory for reading and writing to file. The current directory in Python shell is C:\python38 .

>>> f = open("MyFile.txt") # Open MyFile.txt from the current directory for reading >>> f = open("MyFile.txt", 'w') # Open MyFile.txt from the current directory for writing # perform file operations using f >>> f.close() 

The file operations can raise exceptions if something goes wrong. So, it is recommended to use try-except-finally to handle exceptions and closing a file object.

try: f = open("MyFile.txt") # Open MyFile.txt from the current directory for reading # perform file operations using f except: # handle exceptions finally: f.close() 

The following example opens files for read, write or update operations.

>>> f = open("C:\MyFile.txt") # open for reading >>> f = open("C:\MyFile.txt",'w') # open for writing >>> f = open("C:\MyFile.txt", 'x') # open for exclusive creation >>> f = open("C:\MyFile.txt", 'a') # open for writing, appending to the end of file >>> f = open("C:\MyApp.exe", 'b') # open in binary mode for read >>> f = open("C:\myimage.jpg", 'rb') # open file in binary mode for read and write >>> f = open("C:\MyFile.txt", 't') # open in text mode for read >>> f = open("C:\MyFile.txt", mode='r', encoding='utf-8') # open for reading with utf-8 encoding >>> f = open("C:\MyFile.txt", '+') # open for reading or writing >>> print(type(f) >>> f.close() # closing file after file operations 

Источник

Python File Open

Assume we have the following file, located in the same folder as Python:

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the file:

Example

If the file is located in a different location, you will have to specify the file path, like this:

Example

Open a file on a different location:

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters you want to return:

Example

Return the 5 first characters of the file:

Read Lines

You can return one line by using the readline() method:

Example

Read one line of the file:

By calling readline() two times, you can read the two first lines:

Example

Read two lines of the file:

By looping through the lines of the file, you can read the whole file, line by line:

Example

Loop through the file line by line:

Close Files

It is a good practice to always close the file when you are done with it.

Example

Close the file when you are finish with it:

Note: You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью