Python(六)IO编程

1.打开文件

>>> f=open('C:/Xilinx/input1.txt','r')
>>> f.read()

r表示读的意思

>>> f.read()

将内容读取到内存

>>> f.close()

关文件
为了保证无论能不能读取文件都能把它关闭

try:
    f = open('/path/to/file', 'r')
    print(f.read())
finally:
    if f:
        f.close()

由于这种写法很繁琐,所以用以下写法代替

with open('/path/to/file', 'r') as f:
    print(f.read())

2.stringIO

>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue())
hello world!

猜你喜欢

转载自blog.csdn.net/qq_37282683/article/details/88541536
今日推荐