码迷,mamicode.com
首页 > 编程语言 > 详细

【python】IO系列

时间:2017-05-10 13:06:53      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:byte   char   ddr   1.2   seq   nes   读取   :link   config   

1. 文件IO

1.1 file read

样本C:\FILE\ifconfig.txt

root@webserver1 test# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:50:56:A2:14:55  
          inet addr:10.180.137.68  Bcast:10.180.255.255  Mask:255.255.0.0
          inet6 addr: fe80::250:56ff:fea2:1455/64 Scope:Link
file.readline([size])
读取指定size bytes的整行,返回字符串
with open("C:\FILE\ifconfig.txt") as f:
    print f.name   
    print repr(f.readline())

执行结果

C:\Python27\python.exe C:/PycharmProjects/p3/src/pyproject1/iotest/fileIOtest.py
C:\FILE\ifconfig.txt
‘[root@webserver1 test]# ifconfig\n‘

file.read([size])

 

读取指定size bytes的所有直到EOF,返回字符串

 

 

with open("C:\FILE\ifconfig.txt") as f:
    print f.name
    print repr(f.read())    

 

运行结果

C:\Python27\python.exe C:/PycharmProjects/p3/src/pyproject1/iotest/fileIOtest.py
C:\FILE\ifconfig.txt
‘root@webserver1 test# ifconfig\neth0      Link encap:Ethernet  HWaddr 00:50:56:A2:14:55  \n          inet addr:10.180.137.68  Bcast:10.180.255.255  Mask:255.255.0.0\n          inet6 addr: fe80::250:56ff:fea2:1455/64 Scope:Link\n ‘

Process finished with exit code 0

file.readlines([sizehint])

 

读取指定size bytes的所有直到EOF,返回每行构成的list
with open("C:\FILE\ifconfig.txt") as f:
    print f.name
    print repr(f.readlines())

运行结果

C:\Python27\python.exe C:/PycharmProjects/p3/src/pyproject1/iotest/fileIOtest.py
C:\FILE\ifconfig.txt
[‘root@webserver1 test# ifconfig\n‘, ‘eth0      Link encap:Ethernet  HWaddr 00:50:56:A2:14:55  \n‘, ‘          inet addr:10.180.137.68  Bcast:10.180.255.255  Mask:255.255.0.0\n‘, ‘          inet6 addr: fe80::250:56ff:fea2:1455/64 Scope:Link\n‘, ‘ ‘]

1.2 file write 

Unix/Linux系统里,每行结尾只有“<换行>”,即“\n”;

Windows系统里面,每行结尾是“<回车><换行>”,即“\r\n”;

Mac系统里,每行的结尾是“"<回车>”,即“\r”

file.write(str)

f = open("C:\FILE\ifconfig2.txt", ‘w+‘)
f.write("foooo" + "\n")
f.write("barr")
f.close()
C:\FILE\ifconfig2.txt
foooo
barr

file.writelines(sequence)

 

f = open("C:\FILE\ifconfig2.txt", ‘w+‘)
towrite = ["ffffffoooo\n","barbarbar\n","foobarfoobar"]
f.writelines(towrite)
f.close()

 

C:\FILE\ifconfig2.txt
ffffffoooo
barbarbar
foobarfoobar

 

【python】IO系列

标签:byte   char   ddr   1.2   seq   nes   读取   :link   config   

原文地址:http://www.cnblogs.com/AlexBai326/p/6835037.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!