Python file I/O 2018-07-31

Source: Internet
Author: User
Tags truncated

1. Print to screen: print

You can pass 0 or more comma-separated expressions to print, print converts the passed expression into a string expression, and writes the result to standard output:

# -*- coding: UTF-8 -*-                                          print "Hello",",World",123
[email protected]:~/code$ python test.py Hello ,World 123
2. Read keyboard input: raw_input input

2.1 raw_input([prompt]) reads a line from the standard input and returns a string (minus line breaks at the end of the row)

# -*- coding: UTF-8 -*-                                          str = raw_input("Please input:")print "What you input is :",str

Output:

[email protected]:~/code$ python test.py Please input:hello worldWhat you input is : hello world

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

# -*- coding: UTF-8 -*-                                          str = input("Please input:")print "What you input is :",str

Output:

[email protected]:~/code$ python test.py Please input:helloTraceback (most recent call last):  File "test.py", line 2, in <module>    str = input("Please input:")  File "<string>", line 1, in <module>NameError: name ‘hello‘ is not defined
    • You can see that the result of entering hello as usual is nameerror, but entering a Python expression is normal
[email protected]:~/code$ python test.py Please input:[x*5 for x in range(2,10,2)]What you input is : [10, 20, 30, 40]
3. Open and Close files

3.1 open , you must first open a file with the built-in open function, create a Files object, and the related method can call it to read and write
file object = open(file_name, [, access_mode][, buffering])
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.


3.2 The resulting file object has the following properties when it is opened
file.closed: Returns if the file has been closed, true otherwise returnsfalse
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, the translation is false otherwise returnedtrue

# -*- coding: UTF-8 -*-                                          fo = open ("a.txt",‘w‘)print "file name:",fo.nameprint "closed or not:",fo.closedprint "access mode:",fo.modeprint "末尾是否强制加空格",fo.softspacefo.close()print "closed or not?",fo.closedprint "file name:",fo.nameprint fo.mode

Output

[email protected]:~/code$ python test.py file name: a.txtclosed or not: Falseaccess mode: w末尾是否强制加空格 0closed or not? Truefile name: a.txtw
4. write()Method

Can write any string to an open folder, Python string can be binary data, not just text, write() will not add line breaks at the end of the string

# -*- coding: UTF-8 -*-fo = open ("a.txt",‘w‘)fo.write("Hello world!!!!")                                      fo.close()
5. read()Method

Reading a string from an open file, the Python string can be binary data, not just text, syntax:
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.

# -*- coding: UTF-8 -*-fo = open ("a.txt",‘r+‘)#fo.write("Hello World!!!") #同时使用的话会导致read()无法读出str = fo.read()                                                  print strfo.close()

Output:

[email protected]:~/code$ python test.py Hello world!!!
6. tell()Method

Returns the current position within the file, that is, the next read and write will occur at the beginning of the file
seek(offset[, from])The method changes the position of the current file, offset represents the number of bytes to move, the from variable specifies the reference position at which to begin moving the byte, or if the from is set to 0, the beginning of the file is the reference position of the moving byte, and if set to 1, the current position is used as the reference position; The end of the file is used as the reference location

# -*- coding: UTF-8 -*-fo = open ("a.txt",‘r+‘)str = fo.read(5)print strposition = fo.tell()print "current position:",positionfo.seek(0,0)str = fo.read(5)                                                 print strfo.close()       

Output:

[email protected]:~/code$ python test.py Hellocurrent position: 5Hello
7. Other related methods of file

7.1 flush() : Flushes the buffer, writes the buffer's data immediately to the file, and empties the buffer, rather than passively waiting for the buffer to write
fileObject.flush()
Progress bar Effect instance:

# -*- coding: UTF-8 -*-import sys,time                                                  for x in range(30):    sys.stdout.write(‘*‘)    sys.stdout.flush()    time.sleep(0.2)
    • Its output is output every 9.2 seconds a *, similar to the progress bar, * * If there is no flush() statement, there will be no progress bar effect, but in the last one-time all output to

The 7.2 next() method is used when the file uses an iterator, which returns the next line of the file and, if it reaches the end (EOF), departs Stopiteration

# -*- coding: UTF-8 -*-                                          fo = open("a.txt","r+")for index in range(5):    line = fo.next()    print "第 %d 行 - %s"%(index, line)fo.close()

Output:

[email protected]:~/code$ cat a.txt This is the first lineThis is the second lineThis is the third lineThis is the forth line[email protected]:~/code$ python test.py 第 0 行 - This is the first line第 1 行 - This is the second line第 2 行 - This is the third line第 3 行 - This is the forth lineTraceback (most recent call last):  File "test.py", line 4, in <module>    line = fo.next()StopIteration
    • You can see that the stopinteration is triggered at the end, and each line in the text is followed by a newline character and print a newline character, so a blank line appears

7.3. readline() method, reads the entire line from the file, including the ' \ n ' character, or returns the number of bytes of the specified size, including the ' \ n ' character if a non-negative integer is specified

# -*- coding: UTF-8 -*-fo = open("a.txt","r+")line = fo.readline()print lineline = fo.readline(5)print line        fo.close()       

Output:

[email protected]:~/code$ python test.py This is the first lineThis

next()and readline() contrast

# -*- coding: UTF-8 -*-fo = open("a.txt","r+")for x in range(10):    line = fo.readline()    

Output:

[email protected]:~/code$ python test.py This is the first lineThis is the second lineThis is the third lineThis is the forth line
    • You can see that readline() when you read the end of the file, you continue to read the blank line, without reporting a stopiteration error.

readlines()the 7.4 method reads all rows (until the end of EOF) and returns the list, which can be handled by the structure of the Python for ... in , which returns none when it encounters the Terminator EOF

# -*- coding: UTF-8 -*-                                          fo = open(‘a.txt‘,‘r‘)print fo.readlines()fo.seek(0,0)for line in fo.readlines():    line = line.strip()    print lineprint fo.close()

Output:

[email protected]:~/code$ python test.py [‘This is the first line\n‘, ‘This is the second line\n‘, ‘This is the third line\n‘, ‘This is the forth line\n‘]This is the first lineThis is the second lineThis is the third lineThis is the forth lineNone

7.5 is truncate([size]) used to truncate text, and if an optional parameter of size is specified, the truncated file is a size character, and if it is not specified, it is truncated from the current position and all characters after the size are deleted

# -*- coding: UTF-8 -*-fo = open(‘a.txt‘,‘r+‘)                                          line = fo.readlines()print linefo.seek(0,0)fo.truncate()line = fo.readlines()print linefo.close()

Output:

[email protected]:~/code$ python test.py [‘This is the first line\n‘, ‘This is the second line\n‘, ‘This is the third line\n‘, ‘This is the forth line\n‘][]

Interception of 10

# -*- coding: UTF-8 -*-                                          fo = open(‘a.txt‘,‘r+‘)line = fo.readlines()print linefo.seek(0,0)fo.truncate(10)line = fo.readlines()print linefo.close()

Output:

[email protected]:~/code$ python test.py [‘This is the first line\n‘, ‘This is the second line\n‘, ‘This is the third line\n‘, ‘This is the forth line\n‘][‘This is th‘]

7.6 writelines([str]) writes a sequence of strings to a file, which can be produced by an iterative object, such as a list of strings. Line breaks need to be made with a newline character \ n.

# -*- coding: UTF-8 -*-                                          fo = open(‘a.txt‘,‘r+‘)seq = [‘Hello\n‘,‘World\n‘,‘Python\n‘]fo.writelines(seq)fo.close()

Output:

[email protected]:~/code$ python test.py [email protected]:~/code$ cat a.txt HelloWorldPython

7.7 Question: write() after the content, the direct read file output will be empty?
This is because the pointer is already at the end of the content, so there are 2 solutions: Close the file first, open before reading, and the second is to use the seek() pointer to go back to the file header
Problem Recurrence:

# -*- coding: UTF-8 -*-fo = open(‘a.txt‘,‘r+‘)seq = [‘Hello\n‘,‘World\n‘,‘Python\n‘]fo.writelines(seq)                                               print fo.read()fo.close()

Output:

Solve:

# -*- coding: UTF-8 -*-fo = open(‘a.txt‘,‘r+‘)seq = [‘Hello\n‘,‘World\n‘,‘Python\n‘]fo.writelines(seq)   fo.seek(0,0) #让指针回到文件头                                            print fo.read()fo.close()

Output:

[email protected]:~/code$ python test.py HelloWorldPython
8. Renaming and deleting files

The Python os module provides a way to help you perform file manipulation, such as renaming and deleting files
8.1 rename() is used to rename a method that requires two parameters, the current file name, and a new filename.

os.rename(current_file_name, new_file_name)

8.2 remove() method, delete file, need to provide the file name to delete as parameter
os.remove(file_name)

# -*- coding: UTF-8 -*-                                          import osos.rename("a.txt","b.txt")os.remove("b.txt")

8.3 mkdir() method to create a new directory under the current directory
8.4 chdir() method to change the current directory
8.4 getcwd() method to display the current working directory
8.4 rmdir() method, delete directory, directory name is passed by parameter, before deleting this directory, all its contents should be cleared

    1. To ensure that the file is closed correctly, whether or not it is an error, we can use the try ... finally to implement
try:    f = open(‘/path/to/file‘, ‘r‘)    print f.read()finally:    if f:        f.close()

But every time this is too tedious to write, you can add a with statement to automatically call the close() F method

with open(‘/path/to/file‘, ‘r‘) as f:    print f.read()

Python file I/O 2018-07-31

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.