python——常见读写文件操作

来源:互联网 发布:aisino a3软件下载 编辑:程序博客网 时间:2024/05/22 15:48
1. write:
file_path="/home/lixinglei/test.txt"
file_content="Test file write!"
output = open(file_path, "w")
output.write(file_content)
output.close()

2. read:
file_path = "/home/lixinglei/test.txt"
input = open(file_path)
f_c = input.read()
input.close()

3. readline:
file_path = "/home/lixinglei/test.txt"
input = open(file_path)
lines = input.readlines()
input.close()
for line in lines:
    print line#如果是在命令行中直接写的,在for循环的内容写完了之后,连续按两次回车即可执行

4. 一次读取一行的方法,称作文件迭代器
file_path = "/home/lixinglei/test.txt"
input = open(file_path)
for line in input:
    print line
原创粉丝点击