Python file processing,

Source: Internet
Author: User
Tags glob

Python file processing,

This article introduces Python file processing knowledge. The specific content is as follows:

1. Common File Operations

Files are common operations in routine programming and are usually used to store data or application system parameters. Python provides the OS, OS. path, shutil, and other modules to process files, including the most common functions such as opening files, reading and writing files, assigning values to files, and deleting files.

1.1 File Creation

Python3. + in addition to the Global file () function in python2, the open () function is retained. You can use the open () function to open or create a file (). This function can specify the processing mode and set the opened file to read-only, write-only, and read/write status. The declaration of open () is as follows:

open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)

Parameter description:

• The parameter file is the name of the opened file. If the file does not exist, open () will create a file named name and then open the file.

• The mode parameter indicates the file opening mode. For the file opening mode, refer to the following content.

• The buffering parameter is used to set the cache mode. 0 indicates no cache; 1 indicates cache; if it is greater than 1, it indicates the buffer size, in bytes.

• The encoding parameter is used to set the character encoding format of the file.

• The open () function returns a file object, which can be used to operate files in various file modes:

'r' open for reading (default)'w' open for writing, truncating the file first'x' create a new file and open it for writing

Create a new file, open and write

'a' open for writing, appending to the end of the file if it exists

Open the file to append

'B' binary mode is enabled in binary mode. You can use 't'text mode (default) '+ 'open a disk file for updating (reading and writing) together with other modes) 'U' universal newline mode (deprecated) supports all line breaks

Note: images, videos, and other files must be read and written in the B mode.

message = '''hello world,\nhello python,\ngood time.'''f = open('test.txt','w')f.write(message)f.close()

Code Description:

• Define a string variable

• Create a file in write-only mode and write

• Write string variables to files

• Close files

1.2 File Reading

You can use the readline (), readlines (), or read () functions to read files.

1. Read by row readline ()

Each time readline () reads a row of a file, it needs to read the file cyclically. However, when the file pointer is moved to the end of the file, reading the file using readline () will cause an error. Therefore, you need to add a judgment statement in the program to determine whether the Time Pointer is at the end of the file and use this statement to interrupt the loop. Example:

# Use readline mode to read files f = open('test.txt ', 'R') while True: line = f. readline () if line: print (line) else: breakf. close () # If line = f. readline (2) indicates that only two bytes of content are read in each loop until the end of the row.

2. multi-row read mode readlines ()

# Multiline File Reading f = open('test.txt ') lines = f. readlines () for line in lines: print (line) f. close ()

3. read ()

The simplest way to read a file is to use read (), read () to read all the content in the file at a time and assign the value to the string variable, however, when the file size is large, it is not recommended to read the file using the read () method, because reading a large amount of content at a time will consume a large amount of memory, affecting the system performance. Example:

# One read File f = open('test.txt ', 'R') lines = f. read () print (lines) f. close ()

File pointer:

With open('test.txt ', 'rb') as src: rd = src. read (100) print (rd) print (src. seek (src. tell () rd = src. read (100) print (rd) print (src. seek (src. tell () # Read 100 bytes each time, and then return the pointer position

4. with Function

Usually we use open () to open a file and assign a value to a string variable to operate the file. Finally, we need to manually close the file, which is a little troublesome to write, the with function can be used to open and close a file and write it on a single function.

With open('test.txt ', 'R') as src: da = src. read () print (da) # open the file in read-only mode and assign it to src. Then, perform operations on the file. The Code is the same as operating the file using open.

1.3 file writing

You can use write () or writelines () to write a file. Write () can write strings to files, while writelines () can write lists to files. Example:

m1 = 'hello world'l1 = ['good','time']f = open('test1.txt','w')f.write(m1)f.writelines(l1)f.close()

File appending:

m1 = 'hello python'f = open('test1.txt','a+')f.write(m1)f.close()

1.4 delete an object

To delete a file, you must use the OS module and the OS. path module. The OS module provides operating system functions such as the system environment, files, and directories. For files, the common OS module functions are as follows:

• OS. access (path, mode) # access according to the permission specified by mode
• OS. chmod (path, mode) # change the file access permission. The mode is represented by a UNIX permission symbol.
• OS. open (filename, flag [, mode = 0777]) # open the file according to the permission specified by mode. By default, read, write, and execute permissions are granted to all users.
• OS. remove (path) # delete the file specified by path
• OS. rename (old, new) # rename a file or directory. old indicates the original file or directory, and new indicates the new file or directory.
• OS. stat (path) # returns all attributes of the file specified by path.
• OS. fstat (path) # return all attributes of the opened file
• OS. startfile (filepath [, operation]) # Start the associated program to open the file. For example, opening an html file will start the IE browser
• OS. tmpfile () # create a temporary file in the temporary directory of the Operating System

Note: The open () function of the OS module is used differently from the built-in open () function.

Common functions of the OS. path module are as follows:

• OS. path. abspath (path) # returns the absolute path of the path.
• OS. path. dirpath (path) # Return the directory path
• OS. path. exists (path) # determine whether a file exists
• OS. path. getatime (filename) # returns the last Object Access time.
• OS. path. getctime (filename) # returns the file creation time.
• OS. path. getmtime (filename) # returns the last modification time of the object.
• OS. path. getsize (filename) # returns the file size.

OS. path judgment Function

• OS. path. isabs (s) # test whether the path is an absolute path
• OS. path. isdir (path) # determine whether the specified path is a directory.
• OS. path. isfile (path) # judge whether the specified path is a file
• OS. path. split (p) # splits the path and returns the result in a list.
• OS. path. splitext (p) # split the file extension from the path
• OS. path. splitdrive (p) # split the drive name from the path
• OS. walk (top, func, arg) # traverse the directory tree

Example:

import osif os.path.exists('../test.txt'):os.remove('test.txt')print('is del')else:print('no')

1.5 File Replication

There are multiple ways to copy files. The first low method is to copy files in read/write mode. Example:

# Use read () and write () to copy files f1 = open('1.txt ', 'R') f2 = open('2.txt', 'w') f2.write (f1.read () f2.close () f1.close ()

Method 2:

The shutil module is another file and directory management interface that provides some functions for copying and directory. The copyfile () function can replicate objects. The declaration of the copyfile () function is as follows:
Shuil. copyfile (src, dst)
• Src indicates the path of the source file. src is a string type.
• Dst indicates the path of the target file. dst is a string type.
• Copy the file pointed by src to the file pointed by dst

Example:

import shutilshutil.move('1.txt','2.txt')

1.6 rename a file

The function rename () of the OS module can be used to rename a file or directory.

import osos.rename('1.txt','11.txt')

You can use the move () function in shutil to rename a file.

import shutilshutil.move('11.txt','1.txt')

Modify the file Suffix:

Import osfiles = OS. listdir ('. ') for filename in files: li = OS. path. splitext (filename) # list of returned file names and suffixes if li [1] = '.html ': newname = li [0] + '.htm' OS. rename (filename, newname)

The glob module is used to match paths and return a list of objects meeting the given conditions. The main function of the glob module is glob (), which returns multiple files that meet the same matching condition. You need to determine whether the above rendering is an html suffix. You can also use the glob () function to directly match the file name. The matching code is as follows:

glob.glob('*.html')

Glob can also perform more matching on the path. For example, match all text files in the directory starting with w on drive C.

glob.glob('C:\\\w*\\*\\txt') 

1.7 search and replace files

You can search for and replace file content by searching and replacing strings. For example, search for the 'hello' string in the htlo.txt file and count the number of times 'hello' appears. The Code is as follows:

python, equal to anything!

The above content introduces the Python file processing knowledge and hopes to help you!

Articles you may be interested in:
  • Example code for reading python files row-by-row Processing
  • Python processes text files to generate files in the specified format
  • Python processes text files and generates files in the specified format
  • Example of python processing PHP array text files
  • Introduction to Python open () File Processing
  • How to process XML files using Python on an instance

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.