Python文件操作

文件操作

=========================================================
一、读文件

在项目Python下创建File目录,在File下创建a.txt和一个.py文件
假设a.txt内容为

jahsfjh
11111111
nmlqlnio
222222
7ihnklj9v
t3yq2gbgcki

示例:

import codecs
f1 = codecs.open('a.txt')
text = f1.read()
print(type(text))
result = text.replace('1','A')
print(result)
print(f1.read())
# print(dir(f1))
f1.close()

总结:
打开文件步骤:
1 open文件
2 文件操作(读/写)
3 关闭文件

codecs 常见的类,这个模块主要用来解决文件乱码的问题
codecs(filename, mode)
r 读
w 写
b 二进制
a 追加

=========================================================

二、写文件
示例:

import codecs
f2 = codecs.open('2.txt','w')
f2.write('Hello world!\n')
f2.write('It is a sunny day!\n')
f2.write('The key in your hands\n')
f2.write('the operation is easy.')
f2.close()

运行后,会自动在当前路径下创建2.txt

#ab用来追加,b表示用二进制形式,更安全

f2 = codecs.open('2.txt','ab')
f2.write('Hello world!\n')
f2.write('It is a sunny day!\n')
f2.write('The key in your hands\n')
f2.write('The operation is easy.\n')
f2.close()

运行后,会在2.txt内将原有内容再写一遍。

学习以下写法

f2.write('Hello {0}\n'.format('blueberry'))
f2.write('Hello %s\n' %'fruits')

 

posted on 2017-10-28 10:03  疯疯小和尚  阅读(109)  评论(0)    收藏  举报

导航