[Python3] Understand the basics of file operations


This is a summary of basic knowledge for working with files in Python.

Target: For those who have started learning Python Operating environment: Python3.8.3 (OS is MacOS)

Read and write files

Open file

open method

--Specify the file to open and how to open it (read / write). --The file object will be returned. --After manipulating the file, you need to execute the close method (to free it from memory).

f = open("filename", "mode")

--Type of "mode"

mode Description
r Read mode.
w Overwrite mode. Discard the existing content.
a Addendum mode. Add to the end of the file.
x Write mode dedicated to creating new files. If the file exists, an error is returned and no writing is done.
r+ Read / write mode.

If omitted, it will be treated as "r".

--"Mode" to handle file types

It can be specified in combination with the above "mode".

mode Description
t Text mode. The default mode for the open method. Change the line feed code from the platform-specific symbol to "\Convert to "n".
b Binary mode. It is recommended to use binary mode except for text files.
with keyword

The with keyword always closes the file object, so it's easier to write than implementing it with try ~ finally.

with open("filename") as f:

File object method


--Only the value specified for size is returned as a character string (in text mode) or bytes object (in binary mode). --If size is omitted or a negative number is specified, the entire contents of the file will be returned. --If the end of the file has been reached, an empty string ('') is returned.

'Hello Pyth'


--Reads only one line from the file and returns it. --Contains a newline character (\ n) at the end (excluding the last line that does not contain a newline character).

>>> f.readline()
'Hello Python\n'
Read multiple lines

--Files can be read efficiently for loop processing. --If you want to handle all the lines in the file in list format, use list (f) or f.readlines ().

>>> for line in f:
...     print(line, end='')
Hello Python
Hello Java
Hello Ruby


--Writes the contents of string to a file and returns the number of characters written. --It will be added every time you call the wite method until the file is closed.

>>> with open("sample.txt", "w") as f:
...     f.write("Japan\n")
...     f.write("USA\n")
...     f.write("China\n")
>>> with open("sample.txt", "r") as f:
...     f.read()


--Returns an integer indicating the current location of the file.

--Return "0" if the current position is the first

>>> with open("sample.txt", "r") as f:
...     f.tell()

――Reading 5 bytes moves the current position

>>> with open("sample.txt", "r") as f:
...     f.read(5)
...     f.tell()

f.seek(offset, whence)

--Calculate the file position by adding the offset value (offset) to the reference point (whence). --Specify 0: start, 1: current position, 2: end for whence. If omitted, it behaves as 0: beginning.

>>> with open("sample.txt", "rb+") as f:
...     f.write(b"0123456789abcdef")
...     f.seek(3)       #3 bytes from the beginning
...     f.read(1)
...     f.seek(-1,2)    #1 byte from the end
...     f.read(1)

in conclusion

This time it was the basic content of the basics. Next, I would like to deepen my understanding of how to handle CSV and json (the library is provided).

Recommended Posts

[Python3] Understand the basics of file operations
[Python3] Understand the basics of Beautiful Soup
Summary of python file operations
Review of the basics of Python (FizzBuzz)
About the basics list of Python basics
Basics of python ①
Check the existence of the file with python
I didn't know the basics of Python
The basics of running NoxPlayer in Python
[Python] Get the character code of the file
File operations in Python
Basics of Python scraping basics
the zen of Python
File operations in Python
# 4 [python] Basics of functions
Basics of python: Output
[Python] Chapter 02-01 Basics of Python programs (operations and variables)
Convert the character code of the file with Python3
[Python] Chapter 02-05 Basics of Python programs (string operations / methods)
Get the update date of the Python memo file.
Template of python script to read the contents of the file
Summary of Python3 list operations
Download the file in Python
[Python] Get the official file path of the shortcut file (.lnk)
About the ease of Python
Let's break down the basics of TensorFlow Python code
python: Basics of using scikit-learn ①
I want to fully understand the basics of Bokeh
14 quizzes to understand the surprisingly confusing scope of Python
About the features of Python
How much do you know the basics of Python?
Basics of Python × GIS (Part 1)
The Power of Pandas: Python
I tried to summarize the string operations of Python
Make the display of Python module exceptions easier to understand
[Understand in the shortest time] Python basics for data analysis
[Note] Import of a file in the parent directory in Python
What beginners learned from the basics of variables in python
Google search for the last line of the file in Python
Basics of Python x GIS (Part 3)
Paiza Python Primer 5: Basics of Dictionaries
Extract the xz file with python
The story of Python and the story of NaN
Easy encryption of file contents (Python)
[Python] The stumbling block of import
First Python 3 ~ The beginning of repetition ~
Save the binary file in Python
Understand the contents of sklearn's pipeline
Existence from the viewpoint of Python
pyenv-change the python version of virtualenv
Getting Started with Python Basics of Python
Change the Python version of Homebrew
The story of the "hole" in the file
[Python] Understanding the potential_field_planning of Python Robotics
Basics of Python x GIS (Part 2)
Extract the targz file using python
Python memo ① Folder and file operations
ORC, Parquet file operations in Python
Python basics
Python basics ④
[Python] Let's reduce the number of elements in the result in set operations