"Python" reads data from a file

Source: Internet
Author: User

Reading data from a file

1.1 Reading the entire file

To read a file, you need a file containing several lines of text (file Pi_desc.txt and file_reader.py in the same directory)

Pi_desc.txt

3.1415926535  8979323846  2643383279  5028841971

file_reader.py

With open ("pi_desc.txt") as File_object:    = file_object.read ()     Print(contents)

We can see that when the file is read, and does not use the Colse () method, then not properly closed file, will not cause the file received corruption? Not here, because we introduced the keyword with in front of the open () method, which works by closing the file without needing access

1.2 File path

When the program reads a text file, if the path is not given, it is retrieved in the current directory, and sometimes we need to read the path in the other folder, for example:

The file pi_desc.txt is now stored in the folder txt

Then we have to modify the code to read the text content:

With open ("txt\pi_desc.txt") as File_object:    = file_object.read ()     Print(contents)

Parameters passed to the open parameter are given relative paths

In Linux and OS X, the path uses a slash (/)

In Windows, a backslash (\) is used, but since the backslash is considered an escape character in Python, it is best for Windows to precede the single (double) quotation mark at the beginning of the path with R

Relative path: That is, the path relative to the program file

Absolute path: The path where text is stored on the hard disk

How do you write a program that uses an absolute path?

With open (R"D:\python\txt\PI_DESC.txt") as File_object:    = File_ Object.read ()    print(contents)

1.3 Line-wise read

When reading a file, you may need to read each line in the file, check the file in each row, or modify the file, so you can use a for loop for the file object

' Txt\pi_desc.txt ' With Open (File_path) as File_object:      for inch file_object:         Print (line)

The results of the program run as follows:

We can see from the running result that there are a lot of blank lines in the middle of the printing result, how are these blank lines coming? Because in this file, there is an invisible line break at the end of each line, and the print statement adds a newline character, there are 2 line breaks at the end of each line: one from the file and one from print, eliminating these line breaks, just using the method Rstrip ()

' Txt\pi_desc.txt ' With Open (File_path) as File_object:      for inch file_object:         Print (Line.rstrip ())

Print results

1.4 Create a list containing the contents of each line of the file

When using the keyword with, the file object returned by open () is available only in the with code block, and if you want to access the contents of the file outside of the With block, you can store the file rows in a list in the with blocks and use the list outside of the with code block

' Txt\pi_desc.txt ' With Open (File_path) as File_object:     = File_object.readlines () for in lines:    Print(Line.rstrip ())

1.5 Using the contents of a file

In the previous section we talked about extracting the data into memory, so we can manipulate the data in whatever way we want.

Need: To print the PI together (remove space) and print its length

' Txt\pi_desc.txt ' With Open (File_path) as File_object:     =" for in lines:    + = line.strip ()print (Pi_str.rstrip ()) Print (Len (Pi_str.rstrip ()))

Note that the last print statement is not indented, and if it is indented, it will be printed once per row

The printing effect is as follows

1.5 reading of large files

Here I first use pi top 10,000 to do the experiment, is not a large file, but relatively large file

Accessories: Click to download

In order not to display the PI 10,000 bit, causing the console to blink, we only show the first 20 bits

' Txt\pi_desc.txt ' With Open (File_path) as File_object:     =" for in lines:    + = line.strip ()print(pi_ Str[:20].lstrip ())

"Python" reads data from a file

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.