File processing in Python
File Files are roughly divided into two types: program files and data files. Program files Refers to the OS and applications and all software related to them. Data file Refers to the original file created by the user, such as captured images and videos, words created on a personal computer, Excel files and sentences.
file format A file is assigned a character string called an extension that indicates the type of the file, and there are applications that correspond to each. You can find out what format the file is by checking the end of the file name, for example, "txt", "xlsx", "jpg", "gif", "PNG".
memory Data is stored electrically and temporarily in memory. The advantage is that it reads and writes at high speed. open() If you want to open the file in Python, use the open function. The open function is one of Python's built-in functions, so you don't need to make any special declarations. You can create, write, read, add, save, etc. new files and receive file objects. The open function can be used in the description below.
Execution method
open ('filename you want to open')
When an error is involved, it seems that you can get it as follows.
try: with open(‘hatamoto’, encoding='utf-8') as fin: pass except FileNotFoundError: print ('The target file was not found')
If you want to specify the option, do as follows.
open('hatamoto', mode='rb')
option | Description |
---|---|
r | Open for reading(Default) |
w | Open for writing and truncate the file first |
x | Open to exclusive generation and fail if the file exists |
a | Open for writing and add to the end if the file exists |
b | Binary mode |
t | Text mode(Default) |
+ | It is for using multiple options. |
The default mode is'rt' The encoding is passed as the third argument, but the default character code is treated as "UTF-8".
Read file
Method | Description |
---|---|
read() | Reads the specified data from the file. The default is to read the entire contents of the file. |
readline() | Read one line from the file |
readlines() | Reads all the contents of the file and makes a line-by-line list. |
Write method
Method | Description |
---|---|
write( | Write a string. If you want to write a numerical value etc., str()Convert to a character string once with. |
writelines() | Write a list of strings together. If you want to write numerical values etc. str()Convert to a character string with. |
Binary files are files other than text files Image data, videos, Excel files, program development files, etc. If you want to open a binary file, use the "b" option. For binary files, you don't need to specify the encoding.
Programming divides the problem into several functions. It seems that the purpose is to make it as easy for humans to understand and test management as possible. I think it is as conceptual as object thinking such as Java.
Recommended Posts