Python read and Write file Operations sample program

Source: Internet
Author: User
Tags in python

In daily operation, without text processing, such as program input data preparation, Python by virtue of its simple and elegant syntax, in the text processing than C + + and other compiled language development efficiency of a large section, the following look at the code

The sample file operation copies the code code as follows: #输入文件 f = open (R ' D:python27pro123.bak ') #输出文件 FW = open (R ' D:python27pro123e.bak ', ' W ') #按行读出所有文本 Lin es = 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 there are two functions written () and Writelines () commonly used for writing files, the difference being that file   Write (str): writes string str to a file file.writelines (seq): Writes the contents of a sequence seq all to a file, both of which write data, do not write line breaks, and, if you need to wrap, manually add ' n ' to the str tail that is written: Line breaks are defined in various operating systems, and Windows newline is ' RN ', Unix/linux's newline character is ' n ', and the Mac's line-feed character is ' r '; In Python, the newline character is treated uniformly, defined as ' n ', when written in text mode, and if it is a Windows system, Python automatically converts n to Rn,mac system; The default read-write file, open operation is opened in text mode: F = open (R ' D: Python27pro123.bak ', ' W ') if you open in binary mode, specify the parameter b:f = open (R ' D:python27pro123.bak ', ' RB ')

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.