1. File operation
- open() function
- fileinput operation file
(1), open() function
Use the open() function to open the file, and use the relevant read/write file content for the program to process and use, and the file can also be regarded as a data type in Python.
The prototype of the open() function is as follows:
- open(file, mode=’r’, buffering=’-1’, encoding=None, errors=None, newline=None, closefd=True, opener=None)
The parameters of the open() function are described as follows:
filename | filename to open |
---|---|
mode | optional parameter, file open mode |
bufsize | optional parameter, buffer size |
encoding | file encoding type |
errors | Coding error handling method |
newline | Controls the behavior of passing newline patterns |
closefd | Controls whether the file is closed cleanly when the file is closed |
mode is the operation mode string for opening the file. Common mode strings are as follows:
pattern character | indicated operation |
---|---|
r | read only (r) |
w | Write only, will clear the file content |
a | Additional data |
b | binary data pattern |
x | Create a new file, writable |
+ | Open file for direct update |
t | text mode (default) |
Common file operations and their functions are described as follows:
file operations | Function description |
---|---|
file.read([n]) | Read the entire file into a string, or specify n bytes |
file.readline([n]) | Read a line of a file into a string |
file.readlines() | Read the entire file line by line into a list |
file.write(s) | write string to file |
file.writelines(lines) | Write a list of line data to the file |
file.close() | close open files |
Example of file reading and writing:
① Use for loop to read and write
file = open('G:\\work\\python\\ClassTest.py', encoding='utf-8')
for line in file.readlines():
print(line, end='')
file.close()
②Use while loop to read and write
file = open('G:\\work\\python\\ClassTest.py', encoding='utf-8')
while True:
line = file.readline()
if not line:
break;
print(line, end='')
file.close()
③Use the with statement to read and write
with file as f:
for lines in f:
print(lines, end='')
(2), fileinput operation file
The fileinput module provides a loop to process the content of one or more files in line mode; it implements lazy iteration over the lines in the file, and does not need to put the file content into memory when reading, which improves program efficiency;
The commonly used functions of the fileinput module are:
- input() : Returns an object used to iterate over all lines in one or more files;
- filename() : returns the name of the current file;
- lineno() : returns the number of lines currently read;
- isfirstline() : Returns whether the current line is the first line of the file;
- filelineno() : Returns the number of lines currently read in the file.
2. Common file and directory operations
(1), get the current path
import os
os.getcwd()
(2), get the contents of the directory
import os
os.listdir(path)
(3), create a directory
import os
os.mkdir(path)
(4), delete the directory
import os
os.rmdir(path)
(5), determine whether it is a directory or a file
import os
os.path.isdir(path)
ps.path.isfile(path)
(6), traverse all files and directories under the directory
import os
os.walk(path)
for i in os.walk('.\\'):
print(i)
os.walk() returns multiple tuples; the first item is the traversed directory name, the second item is the traversed subdirectory list, and the third item is the traversed list of all files
Running result:
('G:\work\python', ['01Python crawler foundation', 'bao', ' pycache ', 'article'], ['ClassTest.py', 'compilePy.py', 'ExpectTest.py' ', 'Html.html', 'ItorTest.py', 'lambdaTest.py', 'MyPyModel.py', 'MyTestPy.py', 'MyTestPy.pyc', 'PrintTest.py', 'py10.py', 'PythonClassTest.py', 'PythonEmail.py', 'PythonImport.py', 'Test.py', 'Test20180222.py'])
('G:\work\python\01Python Crawler Basics', [], [' baiduHtmlGet.py', 'BaiduIndex.html', 'BaiduSearchHtmlIndex.html', 'BaiduSearchIndex.py', 'postTest.py', 'PostTestIndex.html', 'qbHtmlIndex.html', 'qbHtmlIndexGet.py', 'Supporting information Download address.jpg', 'Zero Basic Quick Start Python Web Crawler.ppt'])
('G:\work\python\bao', [' pycache '], ['MyPyModel.py', ' init .py'] )
('G:\work\python\bao\__pycache__', [], ['MyPyModel.cpython-36.pyc', 'init .cpython-36.pyc'])
('G:\work\python\__pycache__', [], ['ClassTest.cpython-36.pyc', 'MyPyModel.cpython-36.pyc'])
('G :\work\python\article', [], ['Python.md', 'package.md', 'exception.md', 'module.md', 'generator.md', 'iterator. md'])