Content read operations for Python text files

Source: Internet
Author: User
Tags readline

Python is easy to read the contents of a text file into a string variable that can be manipulated. The file object provides three read methods:. Read (),. ReadLine (), and. ReadLines (). Each method can accept a variable to limit the amount of data read at a time, but they usually do not use a variable. read () reads the entire file at a time, and is typically used to place the contents of the file in a string variable. However, the. Read () generates the most direct string representation of a file's content, but it is unnecessary for sequential row-oriented processing and is not possible if the file is larger than available memory

Open File

print "Opening and closing the file."
text_file = open ("Read_it.txt", "R")
Text_file.close ()

Read one line

print "nreading one line at a time."
text_file = open ("Read_it.txt", "R")
Print Text_file.readline ()
Print Text_file.readline ()
Print Text_file.readline ()
Text_file.close ()

Read a character

print "nreading characters from a line."
text_file = open ("Read_it.txt", "R")
Print Text_file.readline (1)
Print Text_file.readline (5)
Text_file.close ()

Read the entire file output

Print "nreading the entire file into a list."
text_file = open ("Read_it.txt", "R")
lines = Text_file.readlines ()
Print lines
Print Len (lines)
For line in lines:
Print Line
Text_file.close ()

Read a file in one line

print "nlooping through the file, line by line."
text_file = open ("Read_it.txt", "R")
For line in Text_file:
Print Line
Text_file.close ()

Introduction to the Open function used above

F=open ('/tmp/hello ', ' W ')

#open (path + filename, read-write mode)

#读写模式: R Read Only, r+ read/write, w New (will overwrite original file), a append, b binary file. Common patterns

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.