python中的文件读写操作-创新互联

python中如何对文件进行读写操作?针对这个问题,今天小编总结这篇有关文件读写的文章,希望能帮助更多想解决这个问题的朋友找到更加简单易行的办法。

公司主营业务:成都网站建设、网站设计、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联公司是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联公司推出郯城免费做网站回馈大家。

open(filemode='r'buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None)

CharacterMeaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open a disk file for updating (reading and writing)
'U'universal newlines mode (deprecated)

The default mode is 'r' (open for reading text, synonym of 'rt'). For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.

文本读写操作:open(), close(), read(), readlines(),

一、普通操作,open(),read(),close()

#!/usr/bin/python
#coding=utf-8

import logging

try:
	f = open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r')
	print f.read();
	print 'read'
except Exception as e:
	logging.exception(e)
	print 'error'
	raise 
finally:
	if f:
		f.close()
		print 'OK'

运行结果:

#!/usr/bin/python
# -*- coding: utf-8 -*-

class Dict(dict):

    def __init__(self, **kw):
        super().__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value





read
OK

二、read()完后自动close()

with open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r') as f:    
	print (f.read())

运行结果:

#!/usr/bin/python
# -*- coding: utf-8 -*-

class Dict(dict):

    def __init__(self, **kw):
        super().__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

三、为避免read()未知容量的大文件,保险起见用readlines().

print '------------------------------------'
print '-----------------------------------'
f = open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r')
for line in f.readlines():
    print(line.strip())  ##strip会将前面首字符前的空格去掉,造成行句没有缩进
f.close()
print 'over'

运行结果:

------------------------------------
-----------------------------------
#!/usr/bin/python
# -*- coding: utf-8 -*-

class Dict(dict):

def __init__(self, **kw):
super().__init__(**kw)

def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

def __setattr__(self, key, value):
self[key] = value




over

四、读二进制文件,如图片,视频等

>>> f = open('/Users/michael/test.jpg', 'rb')
>>> f.read()
b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' # 十六进制表示的字节

五、write()

with open('/home/seeing-zynq/Documents/Temp/IO/a.txt', 'w') as f:   
    f.write('haha')

with open('/home/seeing-zynq/Documents/Temp/IO/a.txt', 'r') as f:  
    print (f.read())
"file.py" 37L, 758C wri

运行结果:

haha

看完上述内容,你们对python中的文件读写操作大概了解了吗?如果想了解更多相关文章内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。

名称栏目:python中的文件读写操作-创新互联
网页URL:https://www.cdcxhl.com/article6/digcig.html

成都网站建设公司_创新互联,为您提供微信小程序移动网站建设自适应网站响应式网站网站改版品牌网站制作

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

绵阳服务器托管