python读写文件操作示例程序

WBOY
Release: 2016-06-06 11:28:13
Original
1240 people have browsed it

文件操作示例

代码如下:


#输入文件
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()

注意,写入文件常用的有write()和writelines()的两个函数,其区别在于
file.write(str):把字符串str写到文件中
file.writelines(seq):把序列seq的内容全部写到文件中
这两个函数都只是写数据,不会写入换行符,如果需要换行,需手动在写入的str尾部加上'\n':

换行符在各个操作系统中界定的不同,Windows换行符是‘\r\n',Unix/Linux的换行符为'\n',Mac的换行符为'\r';
在python中,对换行符进行了统一处理,定义为'\n',以文本模式写入时,如果是Windows系统,则python会自动将\n转为\r\n,Mac系统类似;
默认的读写文件,打开操作就是以文本模式打开:f = open(r'D:\Python27\pro\123.bak','w')
如果以二进制模式打开,需指定参数b:f = open(r'D:\Python27\pro\123.bak','rb')

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template