Basic Python Tutorial (second edition) Learning note files and materials (11th)

Source: Internet
Author: User
Tags stdin

Basic Python Tutorial (second edition) Learning note files and materials (11th)

Open File:
Open (Filename[,mode[,buffering]])

Mode is the pattern of reading and writing files
F=open (R ' c:\somefile.txt ') #默认是读模式
+ means can read and write, R read mode, W write mode, a append mode, b binary mode;
The newline character is \ r \ n in Windows, and in Unix, Python is automatically converted;

Buffering buffer, 0 for unbuffered, 1 for buffering (use flush or close to write to hard disk);

Sys.stdin standard input; sys.stdout standard output; Sys.stderr error message;

F=open (' Aaa.txt ', ' W ')
F.write (' Hello, ')
F.write (' world! ')
F.close ()

F=open (' Aaa.txt ', ' R ')
F.read (4) # read 4 characters
F.read () # reads the rest of the content

Pipe input/output
Text=sys.stdin.read ()

F.readline () reads a line
F.readline (5) Read 5 character (s)
F.readlines () reads all rows and returns as a list
The f.writelines () input parameter is a list that writes the contents to a file, and no new rows are added;

Close File F.close ()

With open (' Aaa.txt ') as Somefile:
Do_something (Somefile)

Processing by byte
F=open (filename)
Char=f.read (1)
Wile Char:
Process (char)
Char=f.read ()
F.close ()

F=open (filename)
While True:
Char=f.read (1)
If not char:break
Process (char)
F.close ()

Line-by-row processing
F=open (filename)
While True:
Line=f.readline ()
If not line:break
Process (line)
F.close ()

Iterate through each character with read
F=open (filename)
For Char in F.read ():
Process (char)
F.close ()

Iterate rows with ReadLines
F=open (filename)
For line in F.realines ():
Process (line)
F.close ()

Lazy line iterations for large file implementations
Import Fileinput
For line in Fileinput.input (finename):
Process (line)

Iterate files
F=open (filename)
For line in F:
Process (line)
F.close ()

Basic Python Tutorial (second edition) Learning note files and materials (11th)

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.