Read and write Python files

Source: Internet
Author: User

#文件的打开
#file_object = open (file_name,access_mode= ' R ')
# file_name relative path or absolute path Access_mode parameter is not added, then the default is R



# r Opens the file in order to read the file. File pointer at the beginning
Fh=open (' E:/gittest/test/abc.txt ')
Fh.tell ()     #文件对象的tell方法获取文件指针的位置
Fh.read (2) #读取前两个字符.
Fh.read ()

Fh.seek (3) #从开头指针移动3个位置后开始读取

Fh.close ()

STR1 = Fh.readline () #读取一行 contains newline characters

Str.readlines () #读取所有行包含换行符, return to list


# W file exists, content is emptied. File does not exist, create a file
F=open (' tmp ', ' W ')
F.write (' ABCDE ') #会先写入到缓冲区去, this time the view file is not written in
F.flush () #把缓冲区的内容写到磁盘上去


#为了在文件末尾追加内容而打开文件
F=open (' tmp ', ' a ')

#在python3下open函数可以通过encoding参数指定编码方式, but not in 2.
f = open (' Your_file.txt ', ' R ', encoding= ' utf-8 ')


#with Way to open the file, at the end of execution, the system automatically calls F.close ()
With open (' tmp ', ' R ') as F:
FC = F.read ()

#支持多个文件的打开
With open (Infilename) as IFile, open (Outfilename, ' W ') as Ofile:
FC = Ifile.read ()
Ofile.write (FC)

Read and write Python files

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.