Python file read/write

Source: Internet
Author: User

File processing

f= file (' Poem.txt ', ' W ')

# Open for ' W ' riting mode can be read mode (' R '), write mode (' W ') or Append mode (' a ')

F.write (poem) # Write text to file

F.close ()

f = File (' Poem.txt ')

# If no mode is specified, ' R ' ead mode was assumed by default

While True:

line = F.readline ()

If Len (line) = = 0: # Zero length indicates EOF

Break

Print line,

# Notice comma to avoid automatic newline added by Python

F.close () # Close the file

Note that because the content read from the file already ends with a newline character, we use commas on the print statement to eliminate the wrapping.

Storage device

Python provides a standard module, called Pickle. With it you can store any Python object in a file, and then you can take it out intact. This is referred to as a persistent storage object.

There is another module called Cpickle, which functions exactly the same as the Pickle module, except that it is written in C and therefore much faster (1000 times times faster than pickle). You can use either of them, and we'll use the Cpickle module here. Remember, we call these two modules short as pickle modules.

Import Cpickle as P

Shoplistfile = ' Shoplist.data '

# The name of the file where we'll store the object

Shoplist = [' Apple ', ' mango ', ' carrot ']

# Write to the file

f = File (Shoplistfile, ' W ')

P.dump (Shoplist, f) # Dump the object to a file stores objects in open files

F.close ()

Del shoplist # Remove the Shoplist

# Read back from the storage

f = File (Shoplistfile)

Storedlist = P.load (f)

Print Storedlist

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.