[Resolved] Python file operations in Python

Directory Structure:

contents structure [-]

1 Introduction

In Python need for additional modules introduced to carry out file operations, Python has a built-in file manipulation functions (in addition to the built-in file manipulation functions, Python language also provides additional file operations module, which have more powerful).

os module provides a method of operating a file system on the portable operating. If you just want to read and write data, you can use the built-in open () method. If you want to operate path, you can use os.path module. If you want to read all the data lines on the command line, you can use fileinput module. If you want to create a temporary file or path, you can use the tempfile module. If you want a higher level of file and directory operations, you can use shutil module.

The following began to introduce built-in Open method (explained later in this article there are about os and fileinput modules):

first need to open function takes a file object (file object) with built-in Python.

Built-open function can open a file (File), and then returns a file object (file object), the object file contains a large number of methods and properties, methods and properties can be open file operation.

The closed attribute of a file object indicates whether a file is closed (if closed returns True, otherwise return False). mode, obtain the file open mode. name, get the name of the file.

 

The 2.Python file types

In the Windows operating system, the file may be an image, text, executable, audio, video, and more file formats. But in python, files are divided into two types: one is a text file, and the other is a binary file. Text file consists of rows of characters, at the end of each line of text has a character EOL (End Of Line Character). EOL marks the beginning of the end of the current line and a new line. Different binary files and text files, binary files can only be processed by the application knows the file format.

 

3. Built-in functions of file operations

3.1 open () function

The built-in function open Python opens a file and returns a file object.
Open (File, MODE = 'R & lt', Buffering = -1, encoding = None, errors = None, NEWLINE = None, closefd = True, opener = None)
File: Path to open the file, it is necessary to provide.
mode: open mode, default as r (read-only access)
Buffering: Buffer Mode
encoding: encoding the file name of the operation
errors: An optional string that specifies how to handle the error coding and decoding
newline: line feed control mode behavior
closefd : If false, then it should pass a file descriptor (file descripter) should not be passed in the file name. If True, you must pass the file name. Otherwise an error occurs.
opener: a callable objects,

the above parameter file parameter is required only to provide a, mode parameter specifies the file open mode, then I will detail all of its value.

 

3.2 Mode

Mode represents the file open mode, open methods described above need to use the file open mode (Mode), the open mode parameters are optional, are set forth below in Table Mode values.

mode description
r Open the file in read-only mode. Pointer file will be placed at the beginning of the file. This is the default mode.
rb Open a file in binary format only for reading. The file pointer will be placed at the beginning of the file.
r+ Open the file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+ Opens a file for reading and writing binary format. The file pointer will be placed at the beginning of the file.
w Open a file for writing only. If the file already exists it will be overwritten. If the file does not exist, create a new file.
wb Open a file for writing in binary format only. If the file already exists it will be overwritten. If the file does not exist, create a new file.
w+ Open a file for reading and writing. If the file already exists it will be overwritten. If the file does not exist, create a new file.
wb+ Opens a file for reading and writing binary format. If the file already exists it will be overwritten. If the file does not exist, create a new file.
a Open a file for append. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
from Open a file in binary format for additional. If the file already exists, the file pointer will be placed at the end of the file. In other words, 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. When the file is opened in append mode will be used. If the file does not exist, create a new file for reading and writing.
ab + Open a file in binary format for additional. 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.


Here is a use case:

f = open("test.txt","r")
print(f)
f.close()


In the above introduced, open function returns a file object (File Object). Once we get this file object, you can call the properties and methods of this object on the. The most common method is to read and write up.

 

3.3 Create a text file

In order to increase familiarity with the text file, then we will create their own text files and do some exercises on it. Use a text editor, create a file named testfile.txt of. Then in the same level directory, you can use the following code writing operation of the file

file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close() 

When we open testfile.txt, you can document reads as follows:

$ cat testfile.txt
Hello World
This is our new text file
and this is another line.
Why? Because we can.

 

 

3.4 reads a text file

Read the contents of the file are different ways, if you need to read all of the contents of a file, you can use the read method.

file = open(“testfile.txt”, “r”)
print file.read()
file.close()

You will see testfile.txt all contents of the file will be output.

We can only read the specified number of characters, passing just to the number of characters to be read to the read method before it.

file = open(“testfile.txt”, “r”)
print file.read(5)
file.close()

Output:

Hello

 


If you want to read the contents of a text file line by line, you can use the readline method.

file = open(“testfile.txt”, “r”)
print file.readline()
file.close()

Output:

Hello World 



If you want to return every row in the data file, you can use readlines method.

file = open(“testfile.txt”, “r”)
print file.readlines()
file.close()

Output:

[‘Hello World’, ‘This is our new text file’, ‘and this is another line.’, ‘Why? Because we can.’] 

 

3.5 circular file objects

If you want each row of data more efficient circulation file, you can use the loop, loop code is not only simple to use and easy to read.

file = open(“testfile.txt”, “r”)
for line in file:
    print line
file.close()

Output:

Hello World
This is our new text file
and this is another line.
Why? Because we can. 

 

3.6 close the file

Upon completion of operation on the file, it can be used close () method to close the file. It will completely close the file, interruption in use of resources, and these resources will be returned to the system.

After you are finished using the file, remember to call the close () method. After the call to close (), any operations on the file object (file object) are illegal.

After all the above cases, each time we have finished using the file object calls too close () method, which is a very good habit.

 

3.7 With Statement

With statement can be applied to the file object (file object), the with statement syntax clearer. The advantage of using with the statement that any open files are automatically closed, so do not worry about the release of a problem with the use of resources.

With statement to open the file format:
with Open ( "filename") AS File:

The following is a complete case:

with open(“testfile.txt”) as file:  
    data = file.read()
    //do something with data 

In the case of the above code, we did not use close () to close the file object. This is because with the statement will automatically help us close, programmers will be able to focus more on business logic code.

The following is a case of circular file content:

with open(“testfile.txt”) as f:
    for line in f:
        print line, 

 

4.os module

os module provides functions that interact with the operating system, OS Python is a standard component modules. This module provides portability file operating method. os and os.path module contains a number of methods can interact with the operating system files.

 

os.name

Import the module name of the operating system, windows are nt, linux is posix

Import os
 Print (os.name) # Windows is nt, linux is posix

Output:

posix

 

 

os.getcwd()

The os.getcwd () function returns the current working directory (Current Working Directory, CWD)

Import os
 Print (os.getcwd ())
 # print the current absolute path 
# os.path.abspath ( '.')  
 
# Print files and folders in the path 
# the os.listdir ( '.')

Output:

/home/user/test

 

 

os.popen ()

The method opens a conduit connected to the command line, the reader of the duct depends on the open mode.
os.popen, (Command [, MODE [, bufsize]])
MODE (open mode) and bufsize not necessarily be provided. If the open mode is provided, the default is "r", which is a read-only mode (read only).
Case:

import os
fd = "a.txt"
 
# Popen () and open () is similar to 
File Open = (FD, ' W ' )
file.write("Hello")
file.close()
file = open(fd, 'r')
text = file.read()
print(text)
 
# Popen () provides direct access to files conduit 
File = os.popen, (FD, ' W ' )
file.write ( " the Hello " )
 # other operating 
# close the file 
file.close ()

 

os.close()

If a file is to use the open () open, you can only use the close () closed. However, if a file is by os.popen (), then you can use the close () or os.close () method. If we try to use os.close () to close an open () to open the file, it will throw an error:

import os
FD = " a.txt " 
File = open (FD, ' R & lt ' ) # used to open the file open 
text = File.read ()
 Print (text)
os.close (File) # use os.close () closes the file

Output:

Traceback (most recent call last):
  File "/home/user/test/a.py", line 6, in
    os.close(file)
TypeError: an integer is required (got type _io.TextIOWrapper)

 

 

os.rename()

You can use os.rename () Rename the file name, the name of the file must exist and the user should have permission to change the file name.

import os
fd = "a.txt"
os.rename(fd,'New.txt')
os.rename(fd,'New.txt')

Output:

Traceback (most recent call last):
  File "/home/user/test/a.py", line 3, in
    os.rename(fd,'New.txt')
FileNotFoundError: [WinError 2] The system cannot find the
file specified: 'a.txt' -> 'New.txt'

 

 

5.fileInput module

fileinput module can be iterated, traversal operation of the contents of one or more files. Input of the module () function is somewhat similar to the readlines file () method, except that it is an iterative objects, need for loop iteration, which is a one-time read all rows.
The file with a loop through fileinput, formatted output, search, replace, etc., it is very convenient.

Typical usage:

import fileinput
for line in fileinput.input():
    process(line)

 

The basic format:

fileinput.input([files[, inplace[, backup[, bufsize[, mode[, openhook]]]]]])

Parameter Description:

files: # file path list, the default mode is stdin, multi-file [ '1.txt', '2.txt', ...]
InPlace: # whether to write back the results to the standard output file, the default is 0 does not return , is set to return 1
backup: extension # backup file, specify only the extension such as .bak. If the file backup file already exists, it will override the automatic.
bufsize: # buffer size, default is 0, if the file is large, this parameter can be modified, to the general default
mode: # read-write mode, read-only default
openhook: all files # for controlling the opening of the hook, such as He said coding mode;

Common Functions

function description
fileinput.input() It returns an object that can be used for loop through
fileinput.filename() Returns the name of the current file
fileinput.lineno() Returns the number of rows have been read (or number)
fileinput.filelineno() Returns the line number of the currently read
fileinput.isfirstline() Check the current row is the first line of the file
fileinput.isstdin() It determines whether the last row read from stdin
fileinput.close() Turn off the queue



# Test.py 
# --- sample files --- 
c: Python27> 1 of the type .txt
first
second

c:Python27>type 2.txt
third
fourth
# --- sample file --- 
Import the FileInput

def process(line):
    return line.rstrip() + ' line'

for line in fileinput.input(['1.txt','2.txt'],inplace=1):
    print process(line)

# --- resulting output --- 
c: Python27> 1 of the type .txt
first line
second line

c:Python27>type 2.txt
third line
fourth line
# --- --- output results

 

Reference article:

https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
https://www.geeksforgeeks.org/os-module-python-examples/
https://www.2cto.com/kf/201412/361320.html

Guess you like

Origin www.cnblogs.com/HDK2016/p/11076216.html