Detailed Python IO programming

File read and write

Read file###

try:
 # utf8 under windows
 f =open('./README.md','r', encoding='utf8', errors='ignore')print(f.read())finally:
 f and f.close()

# Simplify with
withopen('./README.md','r', encoding='utf8')as f:print(f.read())

# Iteratively read large files
withopen('./README.md','r', encoding='utf8')as f:
 # readline()You can read one line at a time
 for line in f.readlines():
 # Put at the end'\n'Delete
 print(line.strip())
  
# Read binary file
f =open('/Users/michael/test.jpg','rb')
f.read() # b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' #Hexadecimal representation of bytes

Write file

Writing a file is the same as reading a file. The only difference is that when the open() function is called, the identifier'w' or'wb' is passed in, which means writing a text file or writing a binary file.

You can call write() repeatedly to write to the file, but you must call f.close() to close the file. When we write a file, the operating system often does not write the data to the disk immediately, but puts it in the memory cache, and then writes it slowly when it is free. Only when the close() method is called, the operating system guarantees that all unwritten data is written to the disk. The consequence of forgetting to call close() is that only part of the data may be written to the disk, and the rest is lost. So, still use the with statement to get insurance

withopen('./test2.md','a', encoding='utf8')as f:
 f.write('Hello, python!')
 
# Character replacement in the file, replace hello with hi, and then read the content into the memory
withopen('test.txt','r')as f:
 s = f.readlines()
# Then open the file, replace the content in your memory with replace, and write to the file
withopen('test.txt','w')as w:for i in s:
 w.write(i.replace('Hello there','hi'))

StringIO and BytesIO

StringIO

Read and write str in memory.

from io import StringIO
f =StringIO()
f.write('hello')
f.write(' ')
f.write('world!')print(f.getvalue()) #The method is used to obtain the written str.

f =StringIO('Hello!\nHi!\nGoodbye!')while True:
 s = f.readline()if(s ==''):breakprint(s.strip())

BytesIO

Read and write bytes in memory

from io import BytesIO
f =BytesIO()
f.write('Chinese'.encode('utf-8')) #What is written is not str, but UTF-8 bytes of encoding.
print(f.getvalue())

f =BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
f.read() # b'\xe4\xb8\xad\xe6\x96\x87'

Operating files and directories##

import os
os.name #If it is posix, it means that the system is Linux, Unix or Mac OS X; if it is nt, it is a Windows system.
os.uname() #Note uname()Function is not available on Windows

Environment variable

The environment variables defined in the operating system are all saved in the variable os.environ

import os
os.name
' nt'
os.environ #Get environment variables
os.environ.get('PATH')
os.environ.get('x','default')

Manipulate files and directories

Part of the functions for manipulating files and directories is placed in the os module, and part is placed in the os.path module

# View the absolute path of the current directory:
os.path.abspath('.')
# Current directory name
os.path.dirname(os.path.abspath(__file__))
# Create a new directory in a directory, first show the full path of the new directory:
os.path.join('/Users/michael','testdir') # '/Users/michael/testdir'
# Then create a directory:
os.mkdir('/Users/michael/testdir')
# Delete a directory:
os.rmdir('/Users/michael/testdir')
# Path split
os.path.split('/Users/michael/testdir/file.txt')
# Get file extension
os.path.splitext('/path/to/file.txt')
# Rename file
os.rename('test.txt','test.py')
# Delete file
os.remove('test.py')
# OS module
# The os module is to operate the operating system. To use this module, you must first import the module:
import os
# getcwd()Get current working directory(The current working directory is the folder where the current file is located by default)
result = os.getcwd()print(result)
# chdir()Change current working directory
os.chdir('/home/sy')
result = os.getcwd()print(result)open('02.txt','w')
# If you write the complete path during operation, you do not need to consider the default working directory.,Follow the actual writing path
open('/home/sy/download/02.txt','w')
# listdir()Get the name list of all contents in the specified folder
result = os.listdir('/home/sy')print(result)
# mkdir()Create folder
# os.mkdir('girls')
# os.mkdir('boys',0o777)
# makedirs()Create folders recursively
# os.makedirs('/home/sy/a/b/c/d')
# rmdir()Delete empty directory
# os.rmdir('girls')
# removedirs recursively delete folders must be empty directories
# os.removedirs('/home/sy/a/b/c/d')
# rename()File or folder rename
# os.rename('/home/sy/a','/home/sy/alibaba'
# os.rename('02.txt','002.txt')
# stat()Get file or folder information
# result = os.stat('/home/sy/PycharmProject/Python3/10.27/01.py)
# print(result)
# system()Execute system commands(Hazard function)
# result = os.system('ls -al') #Get hidden files
# print(result)
# Environment variable
'''
Environment variables are a collection of commands
The environment variable of the operating system is a collection of directories where the operating system searches for commands when executing system commands
'''
# getenv()Get system environment variables
result = os.getenv('PATH')print(result.split(':'))
# putenv()Add a directory to the environment variable(Temporary increase is only valid for the current script)
# os.putenv('PATH','/home/sy/download')
# os.system('syls')
# exit()Command to exit the terminal
# Common values in the os module
# curdir represents the current folder.Indicates that the current folder can be omitted under normal circumstances
print(os.curdir)
# pardir represents the upper level folder..Indicates that the previous folder cannot be omitted!print(os.pardir)
# os.mkdir('../../../man')#The relative path is searched from the current directory
# os.mkdir('/home/sy/man1')#The absolute path is searched from the root directory
# name Gets the name string representing the operating system
print(os.name) #posix -linux or unix system nt-window system
# sep gets the system path interval symbol window- \ linux -/print(os.sep)
# extsep Get the interval symbol between the file name and suffix window& linux -.print(os.extsep)
# linesep get the newline symbol of the operating system window-  \r\n linux/unix -  \n
print(repr(os.linesep))
# Import the os module
import os
# The following content is os.Content in the path submodule
# abspath()Convert relative path to absolute path
path ='./boys'#relatively
result = os.path.abspath(path)print(result)
# dirname()Get the directory part of the full path&basename()Get the main part of the full path
path ='/home/sy/boys'
result = os.path.dirname(path)print(result)
result = os.path.basename(path)print(result)
# split()Cut a complete path into a directory part and a main part
path ='/home/sy/boys'
result = os.path.split(path)print(result)
# join()Combine 2 paths into one
var1 ='/home/sy'
var2 ='000.py'
result = os.path.join(var1,var2)print(result)
# splitext()Cut a path into file suffix and other two parts,Mainly used to get the file suffix
path ='/home/sy/000.py'
result = os.path.splitext(path)print(result)
# getsize()Get the size of the file
# path ='/home/sy/000.py'
# result = os.path.getsize(path)
# print(result)
# isfile()Check if it is a file
path ='/home/sy/000.py'
result = os.path.isfile(path)print(result)
# isdir()Check if it is a folder
result = os.path.isdir(path)print(result)
# islink()Check if it is a link
path ='/initrd.img.old'
result = os.path.islink(path)print(result)
# getctime()Get create time
# getmtime()Get modify time
# getatime()Get active time
import time
filepath ='/home/sy/download/chls'
result = os.path.getctime(filepath)print(time.ctime(result))
result = os.path.getmtime(filepath)print(time.ctime(result))
result = os.path.getatime(filepath)print(time.ctime(result))
# exists()Check if a path really exists
filepath ='/home/sy/download/chls'
result = os.path.exists(filepath)print(result)
# isabs()Check whether a path is an absolute path
path ='/boys'
result = os.path.isabs(path)print(result)
# samefile()Check if the two paths are the same file
path1 ='/home/sy/download/001'
path2 ='../../../download/001'
result = os.path.samefile(path1,path2)print(result)
# os.environ is used to get and set the built-in values of system environment variables
import os
# Get system environment variable getenv()effect
print(os.environ['PATH'])
# Set system environment variable putenv()
os.environ['PATH']+=':/home/sy/download'
os.system('chls')
# List current directory file name
[ x for x in os.listdir('.')if os.path.isdir(x)]
# List all.py file
[ x for x in os.listdir('.')if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
# walk returns: tupple(dirpath: path,dirnames: list of directories under the path, filenames:List of files under this path)for fpathe,dirs,fs in os.walk(path):for f in fs:print(os.path.join(fpathe,f))

Note: There is no need to split the path by directly splicing strings. This can correctly handle the path separators of different operating systems;

Recommended Posts

Detailed Python IO programming
Python IO
Python network programming
Detailed explanation of Python IO port multiplexing
12. Network Programming in Python3
Detailed Python loop nesting
Python GUI interface programming
Talking about Python functional programming
Python programming Pycharm fast learning
Google Python Programming Style Guide
Python3 script programming commonly used.md
Analysis of Python object-oriented programming
XTU programming Python training three
Black Hat Programming Application Python2
Detailed explanation of python backtracking template
Detailed implementation of Python plug-in mechanism
Detailed explanation of python sequence types
Python embeds C/C++ for detailed development
Detailed sorting algorithm (implemented in Python)
Python error handling assert detailed explanation
Black hat programming application of Python1
Detailed usage of dictionary in Python
How to understand python object-oriented programming
Python classic programming questions: string replacement
Detailed tutorial on installing python3.7 for ubuntu18
Can I learn python without programming foundation
Detailed analysis of Python garbage collection mechanism
Python from attribute to property detailed explanation
Detailed usage of Python virtual environment venv
Analysis of common methods of Python multi-process programming
Detailed explanation of -u parameter of python command
Detailed explanation of Python guessing algorithm problems