Python File IO

Source: Internet
Author: User

Python file I/O Print to screen

The simplest way to output this is to use the print statement, which you can pass 0 or more comma-separated expressions. This function converts the expression you pass to a string expression and writes the result to the standard output as follows:

#!/usr/bin/python# -*- coding: UTF-8 -*- print ("Python 是一个非常棒的语言,不是吗?")

The following results are produced on your standard screen:

Python 是一个非常棒的语言,不是吗?
Reading keyboard input

The Python2 provides two built-in functions to read a line of text from the standard input, and the default standard input is the keyboard. As follows:

    • Raw_input
    • Input

Only the raw_input in the Python3 are provided in input and Python2.

Raw_input function

The Raw_input ([prompt]) function reads a line from the standard input and returns a string (minus the end of the newline character):

#!/usr/bin/python# -*- coding: UTF-8 -*- str=raw_input("请输入:");print"你输入的内容是: "str

This will prompt you to enter any string and then display the same string on the screen. When I enter "Hello python! ", its output is as follows:

请输入:Hello Python!你输入的内容是:  Hello Python!
Input function

The input ([prompt]) function is basically similar to the raw_input ([prompt]) function, but input can receive a Python expression as input and return the result of the operation.

#!/usr/bin/python# -*- coding: UTF-8 -*-  str = input("请输入:");print "你输入的内容是: ", str

This will produce the following results for the input:

请输入:[x*5 for x in range(2,10,2)]你输入的内容是:  [10, 20, 30, 40]
Opening and closing files

You can now read and write to standard inputs and outputs. Now, let's see how to read and write actual data files.

Python provides the necessary functions and methods for basic file operation by default. You can use the file object to do most of the document operations.

Open function

You must first open a file with the Python built-in open () function, create a Document object, and the related method can call it for read and write.

Grammar:

fileobject=open(file_name [, access_mode][, buffering])

The details of each parameter are as follows:

    • file_name: The file_name variable is a string value that contains the name of the file you want to access.
    • Access_mode: Access_mode determines the mode of opening the file: read-only, write, append, etc. All the desirable values are shown in the full list below. This parameter is non-mandatory and the default file access mode is read-only (R).
    • buffering: If the value of buffering is set to 0, there is no deposit. If the value of buffering is 1, the row is stored when the file is accessed. If you set the value of buffering to an integer greater than 1, it indicates that this is the buffer size of the storage area. If a negative value is taken, the buffer size of the storage area is the system default.

Full list of open files in different modes:

Mode Description
R Open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
Rb Opens 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.
r+ Open a file for read-write. The file pointer will be placed at the beginning of the file.
rb+ Opens a file in binary format for read-write. The file pointer will be placed at the beginning of the file.
W Open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file.
Wb Open a file in binary format only for writing. Overwrite the file if it already exists. If the file does not exist, create a new file.
w+ Open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
wb+ Opens a file in binary format for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
A Opens a file for appending. 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 to the existing content. If the file does not exist, create a new file to write to.
Ab Opens a file in binary format for appending. 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 to the existing content. If the file does not exist, create a new file to write to.
A + Open a file for read-write. If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write.
ab+ Opens 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 to read and write.

A good summary of the status of these modes:

A
Mode R r+ W w+ a+
Read + + + +
Write + + + + +
Create + + + +
Covered + +
The pointer is at the beginning + + + +
Pointer at the end + +
Properties of the File object

After a file is opened, you have a files object that you can get various information about the file.

The following is a list of all properties related to the file object:

Properties Description
File.closed Returns true if the file has been closed, otherwise false is returned.
File.mode Returns the access mode of the file being opened.
File.name Returns the name of the file.
File.softspace If the print output must be followed by a space character, false is returned. Otherwise, returns True.

The following example:

# -*- coding: UTF-8 -*-# 打开一个文件=open("foo.txt""wb")print("文件名: ", fo.name)print("是否已关闭 : ", fo.closed)print("访问模式 : ", fo.mode)print("末尾是否强制加空格 : ", fo.softspace)

The result of the above example output:

文件名:  foo.txt是否已关闭 :  False访问模式 :  wb末尾是否强制加空格 :  0
Close () method

The close () method of the file object flushes any information that has not yet been written in the buffer and closes the file, which can no longer be written.

When a reference to a file object is re-assigned to another file, Python closes the previous file. Closing a file with the close () method is a good habit.

Grammar:

fileObject.close();

Example:

# -*- coding: UTF-8 -*-# 打开一个文件=open("foo.txt""wb")print("文件名: "# 关闭打开的文件fo.close()

The result of the above example output:

文件名:  foo.txt

Read and Write files:

The file object provides a series of methods that make it easier to access our files. Take a look at how to read and write to the file using the read () and write () methods.

Write () method

The write () method writes any string to an open file. It is important to note that the Python string can be binary data , not just text.

The Write () method does not add a line break (' \ n ') at the end of the string:

Grammar:

fileObject.write(string);

Here, the parameter being passed is the content to be written to the open file.

Example:

# -*- coding: UTF-8 -*-# 打开一个文件=open("foo.txt""wb""www.baidu.com!\nVery good site!\n");# 关闭打开的文件fo.close()

The above method creates a Foo.txt file, writes the received content to the file, and eventually closes the file. If you open this file, you will see the following:

$ cat foo.txt www.baidu.com!Very good site!
Read () method

The Read () method reads a string from an open file. It is important to note that the Python string can be binary data, not just text.

Grammar:

fileObject.read([count]);

Here, the parameter being passed is the count of bytes to read from the open file. The method reads in from the beginning of the file, and if it does not pass in count, it tries to read as much more content as possible, most likely until the end of the file.

Example:

Here we use the Foo.txt file created above.

#!/usr/bin/python# -*- coding: UTF-8 -*-# 打开一个文件=open("foo.txt""r+")str= fo.read(10);print("读取的字符串是 : "str)# 关闭打开的文件fo.close()

The result of the above example output:

读取的字符串是 :  www.baidu.com

File Location:

File location

tell()The method tells you the current position within the file, in other words, the next read and write will occur after so many bytes at the beginning of the file.

seek(offset [,from])method to change the location of the current file. The offset variable represents the number of bytes to move. The from variable specifies the reference position at which to begin moving bytes.

If from is set to 0, this means that the beginning of the file is used as the reference location for moving bytes. If set to 1, the current position is used as the reference location. If it is set to 2, then the end of the file will be used as the reference location.

Example:

Just use the file Foo.txt we created above.

#!/usr/bin/python# -*- coding: UTF-8 -*- # 打开一个文件fo = open("foo.txt", "r+")str = fo.read(10);print("读取的字符串是 : ", str) # 查找当前位置position = fo.tell();print("当前文件位置 : ", position) # 把指针再次重新定位到文件开头position = fo.seek(0, 0);str = fo.read(10);print("重新读取字符串 : ", str)# 关闭打开的文件fo.close()

The result of the above example output:

读取的字符串是 :  www.baidu.c当前文件位置 :  10重新读取字符串 :  www.baidu.c
Renaming and deleting files

Python's OS module provides a way to help you perform file processing operations, such as renaming and deleting files.

To use this module, you must first import it before you can invoke the various functions associated with it.

Rename () Method:

The rename () method requires two parameters, the current file name, and a new filename.

Grammar:

os.rename(current_file_name, new_file_name)

Example:

The following example renames a file that already exists test1.txt.

# -*- coding: UTF-8 -*-import# 重命名文件test1.txt到test2.txt。"test1.txt""test2.txt" )
Remove () method

You can delete the file using the Remove () method, and you need to provide the filename to delete as a parameter.

Grammar:

os.remove(file_name)

Example:

The following example deletes a file that already exists test2.txt.

# -*- coding: UTF-8 -*-import# 删除一个已经存在的文件test2.txtos.remove("test2.txt")
Directories in Python:

All files are contained in different directories, but Python is also easy to handle. The OS module has many ways to help you create, delete, and change directories.

mkdir () method

You can use the mkdir () method of the OS module to create new catalogs in the current directory. You need to provide a parameter that contains the name of the directory you want to create.

Grammar:

os.mkdir("newdir")

Example:

The following example creates a new catalog test under the current directory.

# -*- coding: UTF-8 -*-import# 创建目录testos.mkdir("test")
ChDir () method

You can use the ChDir () method to change the current directory. The ChDir () method requires a parameter that you want to set as the directory name of the current directory.

Grammar:

os.chdir("newdir")

Example:

The following example goes to the "/home/newdir" directory.

# -*- coding: UTF-8 -*-import# 将当前目录改为"/home/newdir"os.chdir("/home/newdir")

GETCWD () Method:

The GETCWD () method displays the current working directory.

Grammar:

os.getcwd()

Example:

The following example gives the current directory:

#!/usr/bin/python# -*- coding: UTF-8 -*-import os # 给出当前的目录print os.getcwd()
RmDir () method

The RmDir () method deletes the directory, and the directory name is passed as a parameter.

Before deleting this directory, all of its contents should be purged first.

Grammar:

os.rmdir('dirname')

Example:

The following is an example of deleting the "/tmp/test" directory. The fully compliant name of the directory must be given, otherwise the directory will be searched under the current directory.

# -*- coding: UTF-8 -*-import# 删除”/tmp/test”目录"/tmp/test"  )
Summary of methods related to files and directories
File Method Description
File.close () Close the file. The file can no longer read and write after closing.
File.flush () Refreshes the file internal buffer, directly writes the internal buffer data immediately to the file, rather than passively waits for the output buffer to write.
File.fileno () Returns an integer that is a file descriptor (Descriptor FD Integer) that can be used in some of the underlying operations, such as the Read method of the OS module.
File.isatty () Returns True if the file is connected to an end device, otherwise False is returned.
File.next () Returns the next line of the file.
File.read ([size]) Reads the specified number of bytes from the file, if none is given or is negative.
File.readline ([size]) Reads the entire line, including the "\ n" character.
File.readlines ([Sizehint]) Reads all the rows and returns the list, and, given sizeint>0, sets how many bytes are read at a time, in order to alleviate the read pressure.
File.seek (offset[, whence]) Set the current location of the file
File.tell () Returns the current location of the file.
File.truncate ([size]) Intercepts the file, the truncated byte is specified by size, and the default is the current file location.
File.write (str) Writes a string to the file without a return value.
File.writelines (Sequence) Writes a list of sequence strings to the file and adds a newline character to each line if a line break is required.
Methods of the Directory
Method Description
Os.access (path, mode) Verify permission Mode
Os.chdir (PATH) Change the current working directory
Os.chflags (path, flags) Sets the marker for the path to a numeric marker.
Os.chmod (path, mode) Change permissions
Os.chown (path, UID, GID) Change file Owner
Os.chroot (PATH) Change the root directory of the current process
Os.close (FD) Close File Descriptor FD
Os.closerange (Fd_low, Fd_high) Closes all file descriptors, from Fd_low (inclusive) to Fd_high (not included), and errors are ignored
Os.dup (FD) Copy file Descriptor FD
Os.dup2 (FD, FD2) Copy one file descriptor fd to another FD2
Os.fchdir (FD) Changing the current working directory with file descriptors
Os.fchmod (FD, mode) Change the access permissions for a file, specified by the parameter fd, and the parameter mode is the file access permission under UNIX.
Os.fchown (FD, UID, GID) Modify the ownership of a file, which modifies the user ID and user group ID of a file that is specified by the file descriptor FD.
Os.fdatasync (FD) Forces the file to be written to disk, specified by the file descriptor FD, but does not force the update of the file's state information.
Os.fdopen (fd[, mode[, BufSize]) Create a file object with file descriptor FD and return this file object
Os.fpathconf (FD, name) Returns the system configuration information for an open file. Name is the value of the system configuration retrieved, which may be a string that defines system values, which are specified in many criteria (posix.1, UNIX, UNIX 98, and others).
Os.fstat (FD) Returns the state of the file descriptor FD, like stat ().
OS.FSTATVFS (FD) Returns information about the file system that contains file descriptor FD files, such as STATVFS ()
Os.fsync (FD) Forces files with file descriptor FD to be written to the hard disk.
Os.ftruncate (fd, length) Clip file descriptor fd corresponding file, so it cannot exceed the file size maximum.
OS.GETCWD () Return to current working directory
Os.getcwdu () Returns a Unicode object for the current working directory
Os.isatty (FD) Returns true if the file descriptor FD is open while connected to the TTY (-like) device, otherwise false.
Os.lchflags (path, flags) Set the path to a number tag, similar to Chflags (), but no soft link
Os.lchmod (path, mode) Modify Connection File permissions
Os.lchown (path, UID, GID) Changes the file owner, like Chown, but does not track the link.
Os.link (SRC, DST) Create a hard link named DST, point to parameter src
Os.listdir (PATH) Returns a list of the names of files or folders contained in the folder specified by path.
Os.lseek (FD, POS, how) Set file descriptor fd Current position is POS, how mode modified: Seek_set or 0 sets the computed POS starting from the file; Seek_cur or 1 is calculated from the current position; Os. Seek_end or 2 starts at the end of the file. Effective in Unix,windows
Os.lstat (PATH) Like stat (), but no soft links
Os.major (device) Extract the device major number from the original device number (using St_dev in stat or St_rdev field).
Os.makedev (major, minor) Make an original device number with the major and minor device numbers
Os.makedirs (path[, mode]) Recursive folder creation functions. Like MkDir (), but all Intermediate-level folders that are created need to contain subfolders.
Os.minor (device) Extract the device minor number from the original device number (using St_dev in stat or St_rdev field).
Os.mkdir (path[, mode]) Create a folder named path in the digital mode mode. The default mode is 0777 (octal).
Os.mkfifo (path[, mode]) Create a named pipe, mode is a number, default is 0666 (octal)
Os.mknod (filename[, mode=0600, device]) Create a system node named filename file (file device special file or named pipe).
Os.open (file, flags[, mode]) Open a file and set the required open options, the mode parameter is optional
Os.openpty () Open a new pseudo-terminal pair. Returns the file descriptor for the Pty and TTY.
os.pathconf (path, name) Returns system configuration information for the related file.
Os.pipe () Create a pipeline. Returns a pair of file descriptors (R, W), respectively, for read and write
Os.popen (command[, mode[, BufSize]) Open a pipe from a command
Os.read (FD, N) Reads up to n bytes from the file descriptor fd, returns a string containing the read bytes, and the file descriptor fd corresponding file has reached the end, returning an empty string.
Os.readlink (PATH) Returns the file that the soft link points to
Os.remove (PATH) Deletes a file with path. If path is a folder, it will throw oserror; View the following rmdir () to remove a directory.
Os.removedirs (PATH) recursively deletes the directory.
Os.rename (SRC, DST) Rename a file or directory, from SRC to DST
Os.renames (old, new) Rename the directory recursively, or rename the file accordingly.
Os.rmdir (PATH) Deletes the empty directory specified by path and throws a OSError exception if the directory is not empty.
Os.stat (PATH) Gets the information for the path specified by path, which is equivalent to the stat () system call in the C API.
Os.stat_float_times ([newvalue]) Determines whether Stat_result is time stamped with a float object
OS.STATVFS (PATH) Gets file system statistics for the specified path
Os.symlink (SRC, DST) Create a soft link
OS.TCGETPGRP (FD) Returns the process group associated with the terminal FD one open file descriptor returned by Os.open ()
OS.TCSETPGRP (FD, PG) Sets the process group associated with Terminal FD (an open file descriptor returned by Os.open ()) to pg.
Os.tempnam ([dir[, Prefix]])
Os.tmpfile () Returns a file object with an open mode of (W+B). This file object has no folder entry, no file descriptor, and will be automatically deleted.
Os.tmpnam () Returns a unique path for creating a temporary file
Os.ttyname (FD) Returns a String that represents the terminal device associated with the file descriptor FD. If the FD is not associated with the end device, an exception is thrown.
Os.unlink (PATH) Delete file path
Os.utime (path, times) Returns the time that the specified path file was accessed and modified.
Os.walk (top[, topdown=true[, onerror=none[, Followlinks=false]]) Output the file name in the folder by walking in the tree, up or down.
Os.write (FD, str) Writes a string to the file descriptor FD. Returns the string length actually written

Python File IO

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.