设为首页 收藏本站
查看: 995|回复: 0

[经验分享] Python文件读写

[复制链接]

尚未签到

发表于 2015-4-22 07:05:33 | 显示全部楼层 |阅读模式
  读取文件
  最方便的是一次性读入文件内容并放置到一个大字符串中



all_the_text = open('thefile.txt').read()#文本文件中的所有文本
all_the_text = open('thefile.txt','rb').read()#二进制文件中的所有数据
  为了安全,最好给打开的文件指定一个名字 例如



file_object = open('thefile.txt')
#使用try/finally 语句是为了保证文件对象即使在读取中发生错误也可以被关闭 注意不要把open放到try/finally中
try:
all_the_file = file_object.read()
finally:
file_object.close()
  最简单最快 最具Python风格的是逐行读取 并将内容放到列表中:



list_of_all_the_lines = file_object.readlines()
#这样读出的每行末尾都带有'\n'
  也可以使用以下替代方案



list_of_all_the_lines = file_object.read().splitlines()
list_of_all_the_lines = file_object.read().split('\n')
list_of_all_the_lines = [L.rstrip('\n') for L in file_object]
#最简单的逐行处理文本文件的方法是用
for line in file_object:
line = line.rstrip('\n')#去除每行末尾的'\n'
line = line.rstrip()#去除每行末尾的空白符
process line
  如果选择一次读取文件的一小部分,而不是全部,可以这么写



file_object = open('thefile.txt','rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close()
  复杂的循环最好封装成生成器 但我们只能将逻辑的一部分进行封装 因为生成器的关键字yield 不被允许出现在tyr/finally的子语句try子句中
  我们可以这样做



def read_file_by_chunks(filename,chunksize=100):
file_object = open(filename,'rb')
while True:
chunk = file_object.read(chunksize)
if not chunk:
break
yield chunk
file_object.colse()
  然后我们就可以这样使用



for chunk in read_file_by_chunks('abinfile'):
do_something_with(chunk)
  写入文件
  最简单的将长字符串写入文本的方式




open('thefile.txt','w').write(all_the_text)
open('abinfile','wb').write(all_the_data) #写入二进制到文本
  不过最好还是给文件对象指定一个好名字,这样就可以在完成操作后调用close()关闭文件对象



file_object = open('thefile.txt','w')
file_object.write(all_the_text)
file_object.colse()
  如果要写入字符串列表而不是长字符串



file_object.writelines(list_of_text_strings)
open('abinfile','wb').writelines(list_of_data_string)
  文件打开的一些方式

ModesDescription

r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.


rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.


r+
Opens a file for both reading and writing. The file pointer will be at the beginning of the file.


rb+
Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.


w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.


wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.


w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.


wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.


a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.


ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.


a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.


ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
   file 内建方法

SNMethods with Description

1
file.close()
Close the file. A closed file cannot be read or written any more.


2
file.flush()
Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects.


3
file.fileno()
Return the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system.


4
file.isatty()
Return True if the file is connected to a tty(-like) device, else False.


5
file.next()
Returns the next line from the file each time it is being called.


6
file.read([size])
Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes).


7
file.readline([size])
Read one entire line from the file. A trailing newline character is kept in the string.


8
file.readlines([sizehint])
Read until EOF using readline() and return a list containing the lines. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.


9
file.seek(offset[, whence])
Set the file's current position.


10
file.tell()
Return the file's current position


11
file.truncate([size])
Truncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size.


12
file.write(str)
Write a string to the file. There is no return value.


13
file.writelines(sequence)
Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.
  
   参考 http://www.tutorialspoint.com/python/python_files_io.htm

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-59340-1-1.html 上篇帖子: Python+Django在windows下的开发环境配置图解 下篇帖子: Python 主成分分析PCA
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表