Python read and Write file Operation sample program _python

Source: Internet
Author: User
Tags in python

Example of a file operation

Copy Code code as follows:

#输入文件
f = open (R ' D:\Python27\pro\123.bak ')
#输出文件
FW = open (R ' D:\Python27\pro\123e.bak ', ' W ')
#按行读出所有文本
lines = F.readlines ()
num =-1
For line in lines:
str = ' @SES/%i/'%num
line = Line.replace (' @SES/1/', str)
num = num + 1
#写入文件
Fw.writelines (line)
#关闭文件句柄
F.close ()
Fw.close ()

Note that the two functions commonly used for writing files are write () and Writelines (), and the difference is
File.write (str): write string str to a file
File.writelines (seq): Writes the contents of the sequence SEQ all to the file
Both of these functions write only data, do not write line breaks, and, if a newline is required, manually add ' \ n ' at the end of the written Str:

Line breaks are defined differently in each operating system, and Windows newline is ' \ r \ n ', Unix/linux's newline is ' \ n ', and the Mac's newline character is ' \ R ';
in Python, a newline character is treated uniformly, defined as ' \ n ', when written in text mode, and if it is a Windows system, Python automatically turns \ nthe \r\n,mac system to resemble;
The default read-write file, open operation is opened in text mode: F = Open (R ' D:\Python27\pro\123.bak ', ' W ')
If you open in binary mode, specify the parameter b:f = open (R ' D:\Python27\pro\123.bak ', ' RB ')

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.