Python read-Write file Operation sample program

Source: Internet
Author: User
File Operation Example

The code is 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 write files are commonly used with write () and writelines () two functions, the difference is that
File.write (str): Writes the string str to a file
File.writelines (seq): Writes the contents of a sequence seq to a file
Both functions write data only, do not write line breaks, and if you need to wrap, manually add ' \ n ' to the end of the Str written:

NewLine characters are defined differently in each operating system, Windows line break is ' \ r \ n ', Unix/linux's newline character is ' \ n ', and Mac's line break is ' \ R ';
In Python, the line break is uniformly processed, defined as ' \ n ', when written in text mode, and if it is a Windows system, Python will automatically convert \ n to a \r\n,mac system;
Default read-write file, open operation is open in text mode: F = open (R ' D:\Python27\pro\123.bak ', ' W ')
If open in binary mode, specify parameter B:f = open (R ' D:\Python27\pro\123.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.