python Note 008 - File Operation

Keywords: MySQL encoding Python Attribute Windows

1 File operation... 1

1.1 Open and close files... 1

1.1.2 open function... 1

1.2 Properties of File Objects in Files... 1

1.2.1 Attribute... 1

1.2.2 Method... 2

1.2.3 mode='xx'attribute details... 4

1.3 OS operation files... 6

1 File Operation

1.1 Open and close files

1.1.2 open function

     file = open(file_name [,mode][,buffering]

eg: file = open("test.txt",mode = 'r',encoding = 'utf-8')

Details of parameters:

file_name: File name

mode: This parameter is optional and read-only by default (r). For details, see:

https://www.runoob.com/python/python-files-io.html

Enoding: The encoding of files

How to open a file

Note: f.close() must be written at last. Close the file. You can't read it after closing.

1.2 Properties of File Objects in Files

1.2.1 Attribute

     file = open('a.txt', mode = 'r' , encoding = 'utf-8')

Close the file.close file and return true, otherwise return false

file.name returns the file name

Fle.mode returns the access mode of the opened file

1.2.2 Method

Note: When you finish writing, you must refresh it and close it.

(1) write() method:

The write() method can write any string to an open file. Note: Python characters can be binary data, not just text.

The write() method does not automatically add a newline character (' n') at the end of the string.

def test3():
    f = open("day008/day_008_txt1",mode='w',encoding="utf-8")
    f.write('Mencius moved three times, and Mencius'mother chose to be good.\n educational environment,Multiple relocations')
    #Documentation "\n" The function is to change lines. write()Method does not automatically change lines
    f.flush()  #refresh buffer
    #result = f.read() #This sentence is wrong and cannot be read, because mode='w', read-only mode
    f.close()  #Close files
test3()

(2) read() method: read a string from an open file

def test1():    # Read operation
    f = open('day008/day_008_txt' , mode = 'r',encoding='utf-8')
    result = f.read()
    print(result)
    f.close() # Be sure to remember to write close,And write it to the end.
test1()

 

read(n) reads n characters. If the file is not closed, it will not read when it is read, but will start reading at the last cursor. In fact, all those with'b'are processed non-text. (Contains the following)

Note: In text mode, use "r" and "w" modes without encoding and decoding. But in non-text files, such as videos, music, etc., use'wb'and'rb', because

It is impossible to operate with `w'and `r'. Actually,

(3) close() method:

The close() method of the File object refreshes any unwritten information in the buffer and closes the file so that it cannot be written again after closing.

(4) See () method: Used to move the file to read the pointer to the specified location, that is, the cursor.

Syntax: file.seek(offset[,whence])

Offset: initial offset

whence: Optional, default value is 0. Represents where to start offset; 0 represents the beginning, 1 represents the current location, and 2 represents the end of the file.

_tell(): Get the current position of the cursor

The file.tell() method returns the current location of the file, that is, the current location of the file pointer.

day008/day_008_1.txt file content
The moon of Qin shines yet over the passes of Han,
The Long March has not been returned.
But to make Longcheng fly in,
Don't teach Huma to Duyin Mountain.
def test13():
    f = open('day008/day_008_1.txt',mode='r',encoding='utf-8')
    print(f.name)#file name
    line = f.readline()#Read a row of data in a file
    print('The data read is:%s'%(line))

    #Get the current file location
    path = f.tell()
    print('Current position:%d'%path)
    f.close()#Close files
test13()

Result:

 

_truncate(): truncate files

The file. truncate ([size]) method is used to truncate a file. If there is an optional parameter size, it means that the truncated file is size characters. If no size is specified, it is truncated from the current position; after truncation, all characters after size are deleted.

Note: deeping-bug: In r + mode, if you read the content, no matter how much you read, how many cursors are displayed. Rewriting or manipulating files is done at the end.

1.2.3 mode='xx'attribute details

t

 

Text mode (default).

x

 

Write mode, create a new file, if the file already exists, it will report an error.

b

 

Binary mode.

+

 

Open a file for updates (readable and writable).

U

 

General Line Break Mode (not recommended).

r

 

Open the file read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.

rb

 

Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. Usually used for non-text files such as pictures.

r+

 

Open a file for reading and writing. The file pointer will be placed at the beginning of the file.

rb+

 

Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. Usually used for non-text files such as pictures.

w

 

Open a file for writing only. If the file already exists, open it and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.

wb

 

Open a file in binary format for writing only. If the file already exists, open it and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. Usually used for non-text files such as pictures.

w+

 

Open a file for reading and writing. If the file already exists, open it and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.

wb+

 

Open a file in binary format for reading and writing. If the file already exists, open it and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. Usually used for non-text files such as pictures.

a

 

Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. That is to say, the new content will be written after the existing content. If the file does not exist, create a new file for writing.

ab

 

Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. That is to say, the new content will be written after the existing content. If the file does not exist, create a new file for writing.

a+

 

Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. File opens in additional mode. If the file does not exist, create a new file for reading and writing.

ab+

 

Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

 

1) a or ab:

def test4():    # a or ab For file appending, add new content after existing content
    f = open("day008/day_008_txt1", mode='a', encoding="utf-8")
    f.write("'<The Three-Character Classic:'Mother Ximeng, Choose Neighborhood'")
    f.flush()
    f.close()



def test5():    # w + Writing and Reading (Not often used) Direct coverage
    f = open("day008/day_008_txt1", mode='w+', encoding="utf-8")
    f.write("ah")
    f.flush()
    f.close()


def test6():    # a+ Additional reading
    # a+ Write before read and write after read are not able to get content, not cover.
    f = open("day008/day_008_txt1", mode='a+', encoding="utf-8")
    f.write("Learning and Learning")
    print(f.read())
    f.flush()
    f.close()

1.3 OS operation file

File modification: read the contents of the old file into memory; modify; delete the old file; replace the old file name with the new file name

Disadvantage: Memory overflows easily. Solution: read line by line, change line by line

     for line in file

 1 import os
 2 #Method 1
 3 def test10():
 4     #Open the file and create a new file
 5     with open("day008/day_008_1.txt",mode='r',encoding='utf-8') as f1,\
 6         open("day008/day_008_1_new.txt",mode='w',encoding='utf-8') as f2:
 7 
 8         content = f1.read()
 9         new_content = content.replace('Flying generals','Li Guang') # replace content
10         f2.write(new_content)   # write to f2 in
11     os.remove('day008/day_008_1.txt') #delete original file
12     os.rename('day008/day_008_1_new.txt','A life without a marquis.txt') #
13 
14 # Method 2
15 def test11():
16     f1 = open("day008/day_008_1.txt", mode='r', encoding='utf-8')
17     f2 = open("day008/day_008_1_new.txt", mode='w', encoding='utf-8')
18     for line in f1: #One line, one line, one line
19         new_line = line.replace('Li Guang','Flying generals')
20         f2.write(new_line)
21     os.remove('day008/day_008_1.txt')
22     os.rename('day008/day_008_1_new','Li Guang's Characteristic Shou')
23     f2.flush()
Exercises

 

os modules in Python's standard library contain common operating system functions. This module is very important if you want your program to be platform independent. It allows a program to run in Linux and Windows without any changes or problems.

Following are the modules commonly used in os modules:

 1 #os The commonly used methods in modules are as follows:
 2 import os
 3 def test12():
 4     print('01 ',os.sep) #Operating system-specific path separators can be replaced. windows The following is'\'
 5     print('02 ',os.name) # The string indicates the platform you are using. as Windows,It is'nt',linux/unix User, it is'posix'
 6     print('03 ',os.getcwd()) #Current working directory, current Python Script working directory path
 7     print('04 ',os.putenv('username','username/')) #Setting an environment variable
 8     print('05 ',os.environ['username']) #Getting environmental variables
 9     print('06 ',os.listdir('E:\PythonWork\python1\day008')) #Returns all files and directory names in the specified directory
10     print('07 ',os.curdir) #Return to the current directory ('.')
11     # print(os.remove('E:\PythonWork\python1\day008\008 test')) #Delete a file
12     # print(os.system(command)) # Used to run shell commands
13     # print(os.linesep) #Gives the line terminator used by the current platform. Windows is'rn', Linux is'n',Mac is'r'
14     # print(os.chdir(path)) #Change working directory to path
15 test12()

 

Operating screenshots:

 

Ordinary methods of os.path:

 1 #os.path Common methods:
 2 import os
 3 def test13():
 4     print('01.',os.path.isfile('E:\PythonWork\python1\day008\day_008_File operation.py'))
 5     # Verify that the given path is a file return value True False
 6 
 7     print('02.',os.path.isdir('E:\PythonWork\python1\day008'))
 8    # Verify that the given path is a directory return value True False
 9 
10     print('03.',os.path.exists('E:\PythonWork'))
11     #Check whether the given path really exists
12 
13     print('04.',os.path.getsize('E:\PythonWork'))
14     #Get file size
15 
16     print('05.',os.path.abspath('day_008_File operation.py'))
17     #Get the absolute path of the file
18 
19     print('06.',os.path.normcase('E:\PythonWork\python1\day008\day_008_File operation.py'))
20     #Canonical path string form
21 
22     print('07.',os.path.split('E:\PythonWork\python1\day008\day_008_File operation.py'))
23     #Divide the path into directories and file names and return in tuples
24 
25     print('08.',os.path.splitext('E:\PythonWork\python1\day008\day_008_File operation.py'))
26     #Separating File Name and Extension Name
27 
28     print('09.',os.path.join('E:\PythonWork\python1\day008','day_008_File operation.py'))
29     #Use'\\'Connect directories to file names, or connect directories to directories
30 
31     print('10.',os.path.basename('E:\PythonWork\python1\day008\day_008_File operation.py'))
32     #Return file name
33 
34     print('11.',os.path.dirname('E:\PythonWork\python1\day008\day_008_File operation.py'))
35     # Return file path
36 test13()

Operating screenshots:

 

Reference documents: https://www.cnblogs.com/mufenglin/p/7676160.html

Posted by p3rk5 on Fri, 19 Jul 2019 05:41:19 -0700