Python file io (normal file read/write)

Source: Internet
Author: User

# # Open a file
-fileobj = open (filename, mode)
which
Fileobj is the file object returned by open ()
FileName is the string name of the file
Mode is a substring that indicates the file type and operation
  
-the first letter of mode indicates its operation
-R indicates read
-W indicates write, if the file does not exist, it is created, if present, re-writes the new content
-X means to create and write a file without a file present
-A indicates that if the file exists, append the content to the end of the file

-The second letter of mode is the file type
-T (or omit) represents the text type
-B stands for binary files

# # Write file using write (), close file with close ()

1Poem ="""2 from the original grass, one year old a withered flourish. 3 The wild Fire is endless, the spring breeze blows and is born. 4 Far Fang invaded the ancient road, clear Cui Connect desolate city. 5 send Monarch again, luxuriant full sharpens. 6 """7File_obj = open ("Poems",'WT')#open a text file named ' poem ' and create a ' poem ' If it does not exist8File_obj.write (poem)#Write File9File_obj.close ()#Close File

-You can also write files using print ()

1Poem ="""2 from the original grass, one year old a withered flourish. 3 The wild Fire is endless, the spring breeze blows and is born. 4 Far Fang invaded the ancient road, clear Cui Connect desolate city. 5 send Monarch again, luxuriant full sharpens. 6 """7File_obj = open ("Poems",'WT')#open a text file named ' poem ' and create a ' poem ' If it does not exist8 Print(Poem, file=file_obj)#Write File9File_obj.close ()#Close File

-If you need to write a lot of content, you can write data chunked

1Poem ="""2 from the original grass, one year old a withered flourish. 3 The wild Fire is endless, the spring breeze blows and is born. 4 Far Fang invaded the ancient road, clear Cui Connect desolate city. 5 send Monarch again, luxuriant full sharpens. 6 """7File_obj = open ("Poems",'WT')#open a text file named ' poem ' and create a ' poem ' If it does not exist8 9Start =0TenChunk = 20#write 20 characters at a time One  whileTrue: A     ifStart >Len (poem): -          Break -File_obj.write (poem[start:start+Chunk]) theStart + =Chunk -  -File_obj.close ()#Close File

# # File Read
-Read (): Read () function without parameters reads all the contents of the file at one time

1File_obj = open ("Poems",'RT')#To open a text file using read mode2Poem = File_obj.read ()#Read all the contents of a file3File_obj.close ()#Close File4 Print(poem)5 """6 Output:7 from the original grass, one year old a withered flourish. 8 The wild Fire is endless, the spring breeze blows and is born. 9 Far Fang invaded the ancient road, clear Cui Connect desolate city. Ten send Monarch again, luxuriant full sharpens.  One """

 

-can also be read in chunks

1Poem ="'2File_onj = open ("Poems",'RT')3Chunk = 20#reads 20 characters at a time4  whileTrue:5Frag =File_onj.read (Chunk)6     if  notFrag#calling the Read () function again at the end of the file returns an empty string, not frag true, and execution break7          Break8Poem + =Frag9 Ten Print(poem) One """ A Output: - from the original grass, one year old a withered flourish.  - The wild Fire is endless, the spring breeze blows and is born.  the Far Fang invaded the ancient road, clear Cui Connect desolate city.  - send Monarch again, luxuriant full sharpens.  - """

-A row of reads

1Poem ="'2File_obj = open ('Poems','RT')3  whileTrue:4line =File_obj.readline ()5     if  notLine :6          Break7Poem + = Line8 9 Print(poem)Ten """ One Output: A from the original grass, one year old a withered flourish.  - The wild Fire is endless, the spring breeze blows and is born.  - Far Fang invaded the ancient road, clear Cui Connect desolate city.  the send Monarch again, luxuriant full sharpens.  - """

-use iterators to read files

1Poem ="'2File_obj = open ("Poems",'RT')3  forLineinchFile_obj:#same effect, but shorter code4Poem + = Line5 6 Print(poem)7 """8 Output:9 from the original grass, one year old a withered flourish. Ten The wild Fire is endless, the spring breeze blows and is born.  One Far Fang invaded the ancient road, clear Cui Connect desolate city.  A send Monarch again, luxuriant full sharpens.  - """

-ReadLines (): reads one line at a time and returns a list of single-line strings

1File_obj = open ("Poems",'RT')2Lines =File_obj.readlines ()3 Print(lines)4  forLineinchlines:5     Print(Line, end="')6     7 """8 [' \ n ', ' the grass from the original, one year old and one withered flourish. \ n ', ' The wild Fire is endless, the spring breeze blows and is born. \ n ', ' The Far Fang invaded the ancient road, the fine Cui connect the desolate city. \ n ', ' send monarch again, luxuriant full sharpens. \ n ']9 Ten from the original grass, one year old a withered flourish.  One The wild Fire is endless, the spring breeze blows and is born.  A Far Fang invaded the ancient road, clear Cui Connect desolate city.  - send Monarch again, luxuriant full sharpens.  - """

# # Write () writes a binary file

1 # converting a sequence to binary data 2 f = open ('bin_file'wb')      #  Open file in binary format 3 f.write (bin_data)               #  write 4 f.close ()                       # Close

-Segmented Write

1Bin_data = bytes (range (0, 255))2f = open ('Bin_file','WB')3Chunk = 100#write 100 bytes at a time4offset =05  whileTrue:6     ifOffset >Len (bin_date):7          Break8F.write (Bin_data[offset:chunk +offset])9Offset + =ChunkTen  OneF.close ()

-Read binary files

1 f = open ('bin_file'rb')2 bin_ data = F.read ()3 f.close ()

# # Use with auto close file, auto close file after complete with code block

1With open ("Poems",'RT') as F:2Poem =F.read ()3 4 Print(poem)5 """6 Output:7 from the original grass, one year old a withered flourish. 8 The wild Fire is endless, the spring breeze blows and is born. 9 Far Fang invaded the ancient road, clear Cui Connect desolate city. Ten send Monarch again, luxuriant full sharpens.  One """

This article refers to:

Beauty Bill Lubanovic "Python language and its application"

Python file io (normal file read/write)

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.