File---Python

Source: Internet
Author: User

---restore content starts---

Read file:

Fin=open ("Test.txt")
Read=fin.readline ()-----read a line
For line in Fin:
Print (line)
Fin.close ()

Read=fin.read ()----Read all content

Write file:

Fout=open (' Test.txt ', ' W ')----Erase the original contents of the file and write
Line1= ' Good afternoon '
Fout.write (line1)---Write argument must be a string
Fout.close ()

Fout=open (' Test.txt ', ' a ')----append content to the source file

Format operator---%: Converts an expression to a string

Line= ' in%d years I had spotted%g%s '% (3,0.1, ' camels ')

File name and path:

Import OS----OS W provides functions for manipulating files and directories
CWD=OS.GETCWD ()----Get the current directory

Path=os.path.abspath (' test.txt ')----get the absolute path to the file

Os.path.exists (' test.txt ')----checks if a file or directory exists, returns a Boolean type

Os.path.isdir (' test.txt ')----Check if it is a directory

Os.listdir (CWD)---Returns a list of files in the specified directory

Os.path.isfile (' Test ')---Check if it is a file

Os.path.join (dirname,name)----accept a directory and file name and spell it as a full path

Catching Exceptions:

Try
Fin=open (' Test.txt ')
For line in Fin:
Print (line)
Fin.close ()
Except
Print (' Something is wrong ')

To write a module:

If you have a file: example.py

Importing this file: import example

Using Functions in example.py: Example.linecount ()

Os.path.

File---Python

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.