Python read/Write File Operation example Program

Source: Internet
Author: User

File Operation example

Copy codeThe Code is as follows:
# Input file
F = open (r 'd: \ Python27 \ pro \ 123. bak ')
# Output file
Fw = open (r 'd: \ Python27 \ pro \ 123e. bak ', 'w ')
# Read all text by line
Lines = f. readlines ()
Num =-1
For line in lines:
Str = '@ SES/% I/' % num
Line = line. replace ('@ SES/1/', str)
Num = num + 1
# Writing files
Fw. writelines (line)
# Close the file handle
F. close ()
Fw. close ()

Note: write () and writelines () functions are commonly used to write files. The difference is that
File. write (str): writes the string str to the file.
File. writelines (seq): write all the content of the sequence seq to the file.
Both functions only write data and do not write line breaks. To use line breaks, manually add '\ n' to the end of the written str ':

Line breaks are defined in different operating systems. The Windows line breaks are '\ r \ n', the Unix/Linux line breaks are' \ n', And the Mac line breaks are '\ R ';
In python, line breaks are uniformly processed and defined as '\ n'. If it is written in text mode, python automatically converts \ n to \ r \ n, and the Mac system is similar;
Default read/write file, open in text mode: f = open (r 'd: \ Python27 \ pro \ 123. bak ', 'w ')
If it is enabled in binary mode, you must 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.