Read and write operations for files in Python

Source: Internet
Author: User
This article mainly describes the Python file read and write operations, read data from the file operation method, this article through the combination of examples of text to introduce you very detailed, the need for friends can refer to the next

Reading data from a file

Read the entire file

This assumes that there is a text file named ' Pi_digits.txt ' in the current directory with the following data:

3.1415926535
8979323846
2643383279


With open (' Pi_digits.txt ') as F: # The default mode is ' R ', read-only mode  contents = F.read () # reads the entire contents of  the file print contents # Output When there is a row at the end (read ( The function arrives at the end of the file and returns a null character, showing that the null character is a blank line)  print '------------'  print Contents.rstrip () # Rstrip () function to remove whitespace at the end of the string


3.1415926535
8979323846
2643383279
------------
3.1415926535
8979323846
2643383279

Read row by line

You can read the data line by loop:


With open (' Pi_digits.txt ') as F: for  line1 in F:    print line1 # There is a line break at the end of each line  print '------------' for  line2 In F:    print Line2.rstrip () # Now that the file has been read, line2 points to the end of the text, so there is no output


3.1415926535

8979323846

2643383279

------------

Reading a file is equivalent to having a pointer in the location where the record is read, where the data is read, which way the pointer continues to read from that location, so the output from the second loop in the preceding code is empty. Modify the above code slightly as follows:


With open (' Pi_digits.txt ') as F: for  line1 in F:    print line1  print '------------' with open (' Pi_digits.txt ') As F: # need to reopen text to read for  line2 in F:    print Line2.rstrip () # Remove whitespace at the end of a string


3.1415926535

8979323846

2643383279

------------
3.1415926535
8979323846
2643383279

The above code is equivalent to closing the file after the first read and then reopening it for reading. Reading data row by line can also be used with the ReadLine () function, as follows:


With open (' Pi_digits.txt ') as F:   # ReadLine () reads a row of data each time and points to the end of the line  line1 = F.readline () # reads the first row of data (at which point the first line is already at the end)  line2 = F.readline () # reads from the end of the last read (second row)  print Line1.rstrip ()  print Line2.rstrip ()


3.1415926535
8979323846

Sometimes we want to read all of the data at once and store it separately for subsequent operations, of course, with the above loop, but Python provides an easier way to ReadLines ():


With open (' Pi_digits.txt ') as f:   lines = F.readlines () # reads everything in the text and saves it in a list, each element in the list corresponds to a row of data print lines # Each row of data contains a newline character print '------------' for lines in lines:  print Line.rstrip ()  print '------------' pi_str = ' # Initialize null character for line in lines:  pi_str + = Line.rstrip () #字符串连接print pi_str


[' 3.1415926535\n ', ' 8979323846\n ', ' 2643383279\n ']
------------
3.1415926535
8979323846
2643383279
------------
3.141592653589793238462643383279

Writing data to a file

There are several different modes of writing data, the most common being w ', ' A ', which means erasing the original data and then writing the data to the original data:


filename = ' write_data.txt ' with open (filename, ' W ') as f: # If FileName does not exist it will be created automatically, ' W ' means write data, and the original data in the file will be emptied before writing!  F.write ("I am meringue.\n")  f.write ("I am now studying in njtech.\n")


A text file of ' Write_data.txt ' is created under the current path, and the data is written to the file as follows:

I am meringue.
I am now studying in Njtech.

The following continues to include new data in the file:


with open (filename, ' a ') as F: # ' A ' denotes append, which continues to write data after the original file contents (unclear original data)  F.write ("I Major in machine learning and computer Vision.\n ")


The file contents at this time are:

I am meringue.
I am now studying in Njtech.
I Major in machine learning and computer vision.

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.