美文网首页
Python 文件处理

Python 文件处理

作者: 超人高飞 | 来源:发表于2017-03-27 09:35 被阅读50次
  • 创建文件

f = file('myfile.txt','w')
f.write('hello,baby!')
f.close()
w :写(如果已经存在,会将其覆盖)
r :读
a :追加
w+、a+、r+:读写模式,以文本方式读
wb、rb :读写模式, 以二进制方式读

import time
f = file(‘test.txt’,'w') // 与open(‘test.txt’,'w')没有差别
for i in range(10):
time.sleep(1)
f.write(the %s loops\n'%i)
f.flush()
f.close

  • 遍历文件内容

a =file ('user_info.txt')
for line in a.readlines():
print line
a.close

  • 追加

f = file("text.txt",'a')
f.write("append to the end")
f.colse()

  • 文件内容替换

for line in fileinput.input("filepath",inplace = 1,backeup = ".old"):
line = line.replace("oldtext","newtext")
print line

inplace = 1 替换的内容写会原文件,inplace = 0,如果只打印出来,不写到原文件。
backeup = ".old" 做一个备份。

  • 文件操作函数

file.read() 读取全部文本
file.tell() 返回文件位置 字符数
file.seek(number) 回溯到number 数字符数处
file.truncate(number) 从当前处截断到number字符处

import tab
with open("filepath","r+") as f: 相当于f = open("filepath","r+") ,但是它会自动关闭文件句柄。

相关文章

  • Python 文件处理

    Python 读文件处理 1. readline() with 处理开闭文件&文件异常处理 readline()内...

  • 从Excel到Python (视频)

    Python Pandas处理Excel文件

  • Python 文件处理

    文件的理解 文件是数据的抽象和集合 文本文件 VS. 二进制文件 f.txt 文件保存: "人生苦短, 我用Pyt...

  • Python 文件处理

    文件处理 常用打开文件方式 1.读取文件内容, 模式为 'r' 表示读, 这也是打开的默认方式。 2.如果要创建或...

  • python 文件处理

  • python——文件处理

    1.文件处理 如果报错 说明编码不对。 按正常逻辑来讲,文件是以什么方式存的,就应该用什么方式去读取,比如以gb2...

  • Python 文件处理

    python 文件打开方式 文件打开方式: open(name[,mode[,buf]])name: 文件路径mo...

  • Python 文件处理

    创建文件 f = file('myfile.txt','w') f.write('hello,baby!')f....

  • python 文件处理

    文件处理有三个步骤:1、定义文件路径: 2、打开并保存文件内容。 r:以只读方式打开文件。文件的指针将会放在文件的...

  • Python文件处理

    文件读取 整个读取 两个注意点: 使用关键字with可以自动关闭文件流,如果使用file_object = ope...

网友评论

      本文标题:Python 文件处理

      本文链接:https://www.haomeiwen.com/subject/hinopttx.html