How to read, write, and create files using python

Source: Internet
Author: User
The following small series will introduce a python method for reading, writing, and creating files (required ). I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the operations on files and folders (File operation functions) in python that involve the OS module and the shutil module.

Get the current working directory, that is, the directory path for the current Python script: OS. getcwd ()

Returns all files and directories in the specified directory named OS. listdir ()

The function is used to delete a file: OS. remove ()

Delete multiple directories: OS. removedirs (r "c: \ python ")

Check whether the given path is a file: OS. path. isfile ()

Check whether the given path is a directory: OS. path. isdir ()

Determine whether the path is absolute: OS. path. isabs ()

Check whether the given path is saved: OS. path. exists ()

Returns the directory name and file name of a path: OS. path. split () eg OS. path. split ('/home/swaroop/byte/code/poem.txt') result: ('/home/swaroop/byte/code', 'poem.txt ')

Separation extension: OS. path. splitext ()

Get the path: OS. path. dirname ()

Get File name: OS. path. basename ()

Run the shell command: OS. system ()

Read and set environment variables: OS. getenv () and OS. putenv ()

The line terminator used by the current platform is given: OS. linesep for Windows uses '\ r \ n', Linux uses' \ n', and Mac uses '\ r'

Indicates the platform you are using: OS. name for Windows, it is 'nt ', and for Linux/Unix users, it is 'posix'

Rename: OS. rename (old, new)

Create a multilevel Directory: OS. makedirs (r "c: \ python \ test ")

Create a single directory: OS. mkdir ("test ")

Get file attributes: OS. stat (file)

Modify file permission and timestamp: OS. chmod (file)

Terminate the current process: OS. exit ()

Get file size: OS. path. getsize (filename)


File operations:
OS. mknod ("test.txt") to create an empty file
Fp = open ("test.txt", w) open a file directly. if the file does not exist, create a file.

About open mode:

W open in write mode,
A is opened in append mode (starting from EOF and creating a file if necessary)
R + enabled in read/write mode
W + is enabled in read/write mode (see w)
A + is enabled in read/write mode (see)
Rb is enabled in binary read mode.
Wb is enabled in binary write mode (see w)
AB is enabled in binary append mode (see)
Rb + is enabled in binary read/write mode (see r +)
Wb + is enabled in binary read/write mode (see w +)
AB + is enabled in binary read/write mode (see a +)

Fp. read ([size]) # size indicates the read length, in bytes.

Fp. readline ([size]) # read a row. if the size is defined, only one part of the row may be returned.

Fp. readlines ([size]) # use each row of the file as a member of a list and return this list. In fact, it is implemented by calling readline () cyclically. If the size parameter is provided, size indicates the total length of the read content, that is, it may be read only to a part of the file.

Fp. write (str) # write str to the file. write () does not add a linefeed after str.

Fp. writelines (seq) # write all seq content to a file (multiple rows are written at one time ). This function is only faithfully written without adding anything to the end of each line.

Fp. close () # close the file. Python will automatically close the file after a file is not used, but this function is not guaranteed, it is best to develop your own habit of closing. If a file is closed and operated on it, ValueError is generated.

Fp. flush () # write the buffer content to the hard disk

Fp. fileno () # returns a long integer "file tag"

Fp. isatty () # whether the file is a terminal device file (in unix)

Fp. tell () # return the current position of the file operation mark, starting with the file as the origin

Fp. next () # return the next line and move the operation mark of the file to the next line. Use a file... When a statement such as in file is called, the next () function is called to implement traversal.

Fp. seek (offset [, whence]) # Mark the file operation and move it to the offset position. This offset is generally calculated relative to the beginning of the file, and is generally a positive number. However, if the whence parameter is provided, it is not necessary. if The whence parameter is 0, it indicates that the calculation starts from the beginning, and 1 indicates that the calculation is based on the current position. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the operation mark of the file is automatically returned to the end of the file each time the file is written.

Fp. truncate ([size]) # crop the file to the specified size. the default value is the location marked by the current file operation. If the size is larger than the file size, the file may not be changed depending on the system, or 0 may be used to fill the file with the corresponding size, it may also be added with random content.

Directory operation:
OS. mkdir ("file") to create a directory
Copy a file:
Shutil. copyfile ("oldfile", "newfile") both oldfile and newfile can only be files.
Shutil. copy ("oldfile", "newfile") oldfile can only be a folder. newfile can be a file or a target directory.
Copy folder:
Shutil. copytree ("olddir", "newdir") both olddir and newdir can only be directories, and newdir must not exist
Rename a file (directory)
OS. rename ("oldname", "newname") files or directories all use this command
Move a file (directory)
Shutil. move ("oldpos", "newpos ")
Delete an object
OS. remove ("file ")
Delete directory
OS. rmdir ("dir") can only delete empty directories
Shutil. rmtree ("dir") empty directories and directories with content can be deleted.
Conversion Directory
OS. chdir ("path") change path

Reading and writing Python files

1. open
After opening a file using open, remember to call the close () method of the file object. For example, you can use the try/finally statement to ensure that the file can be closed at last.

File_object = open('thefile.txt ')
Try:
All_the_text = file_object.read ()
Finally:
File_object.close ()

Note: The open statement cannot be placed in the try block, because when an exception occurs when the file is opened, the file object file_object cannot execute the close () method.

2. read files
Read text files
Input = open ('data', 'r ')
# The second parameter defaults to r.
Input = open ('data ')

Read binary files
Input = open ('data', 'RB ')

Read all content
File_object = open('thefile.txt ')
Try:
All_the_text = file_object.read ()
Finally:
File_object.close ()

Read fixed bytes
File_object = open ('abinfile', 'RB ')
Try:
While True:
Chunk = file_object.read (100)
If not chunk:
Break
Do_something_with (chunk)
Finally:
File_object.close ()

Read each line
List_of_all_the_lines = file_object.readlines ()

If the file is a text file, you can directly traverse the file object to get each line:

For line in file_object:
Process line

3. write files
Write a text file
Output = open ('data', 'w ')

Write binary files
Output = open ('data', 'WB ')

Append a file
Output = open ('data', 'W + ')

Write Data
File_object = open('thefile.txt ', 'w ')
File_object.write (all_the_text)
File_object.close ()

Write multiple rows
File_object.writelines (list_of_text_strings)

Note that calling writelines to write multiple rows has a higher performance than using write for one-time writing.

When processing log files, we often encounter the following situation: the log files are huge and it is impossible to read the entire file into the memory at a time for processing, for example, to process a 2 GB log file on a machine with 2 GB physical memory, we may want to process only 200 MB of content at a time.
In Python, the built-in File object directly provides a readlines (sizehint) function to accomplish this. The following code is used as an example:

File = open ('test. log', 'r') sizehint = 209715200 #200 Mposition = 0 lines = file. readlines (sizehint) while not file. tell ()-position <0: position = file. tell () lines = file. readlines (sizehint)

Every time you call the readlines (sizehint) function, it returns about 200 MB of data, and the returned data must be complete row data. In most cases, the number of bytes of the returned data is slightly larger than the value specified by sizehint (except when the last readlines (sizehint) function is called ). Generally, Python automatically adjusts the user-specified sizehint value to an integer multiple of the internal cache size.

File is a special type in python. it is used to operate external files in python programs. In python, everything is an object, and file is no exception. file has the methods and attributes of file. The following describes how to create a file object:


File (name [, mode [, buffering])
The file () function is used to create a file object. a file object is called open (), which may be more vivid. they are built-in functions. Let's take a look at its parameters. Its parameters are all transmitted in the form of strings. Name is the name of the file.
Mode is the open mode. the optional value is r w a U, which represents the mode in which various line breaks are supported for Read (default) writes. If you open a file in w or a mode, if the file does not exist, it is automatically created. In addition, when you open an existing file in w mode, the content of the original file will be cleared, because the operation mark of the initial file is at the beginning of the file, at this time, the write operation will undoubtedly erase the original content. For historical reasons, line breaks have different modes in different systems. for example, in unix, the line breaks are \ n, and in windows, the line breaks are \ r \ n ', opening a file in U mode supports all line breaks. that is to say, '\ R'' \ n' \ r \ n' indicates line breaks, there will be a tuple used to store the line breaks used in this file. However, although there are multiple line breaks, reading python should be replaced by \ n. + B t can be added after the pattern character, indicating that the file can be read and written at the same time and the file can be opened in binary mode and text mode (default.
If buffering is set to 0, no buffer is performed. if it is set to 1, "row buffer" is performed. if it is a number greater than 1, the buffer size is measured in bytes.

File objects have their own attributes and methods. Let's take a look at the file attributes.


Closed # Mark whether the file has been closed and rewritten by close ()
Encoding # file encoding
Mode # Open mode
Name # file name
Newlines # The line feed mode used in the file is a tuple
Softspace # boolean type, generally 0, is said to be used for print

File read/write method:

F. read ([size]) # size indicates the read length, in bytes.
F. readline ([size])
# Read a row. if the size is defined, only one part of the row may be returned.
F. readlines ([size])
# Use each row of the file as a member of a list and return this list. In fact, it is implemented by calling readline () cyclically. If the size parameter is provided, size indicates the total length of the read content, that is, it may be read only to a part of the file.
F. write (str)
# Write str to a file. write () does not add a linefeed after str.
F. writelines (seq)
# Write all seq content to the file. This function is only faithfully written without adding anything to the end of each line.

Other file methods:

F. close ()
# Close the file. Python will automatically close the file after a file is not used, but this function is not guaranteed, it is best to develop your own habit of closing. If a file is closed and operated on it, ValueError is generated.
F. flush ()
# Write the buffer content to the hard disk
F. fileno ()
# Return a long integer "file tag"
F. isatty ()
# Whether the file is a terminal device file (in unix)
F. tell ()
# Return the current position of the file operation mark, starting with the file
F. next ()
# Return the next row and move the operation mark of the file to the next row. When a file is used in a statement such as for... in file, the next () function is called to implement traversal.
F. seek (offset [, whence])
# Move the file to the offset position by marking the operation. This offset is generally calculated relative to the beginning of the file, and is generally a positive number. However, if the whence parameter is provided, it is not necessary. if The whence parameter is 0, it indicates that the calculation starts from the beginning, and 1 indicates that the calculation is based on the current position. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the operation mark of the file is automatically returned to the end of the file each time the file is written.
F. truncate ([size])
# Crop the file to a specified size. the default value is to crop it to the position marked by the current file operation. If the size is larger than the file size, the file may not be changed depending on the system, or 0 may be used to fill the file with the corresponding size, it may also be added with random content.

The above python read/write and file creation method (required) is all the content shared by the editor. I hope to give you a reference and support for PHP.

For more articles about how to read, write, and create files using python, refer to the PHP Chinese website!

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.