Python——文件IO

xiaoxiao2021-02-27  289

打印到屏幕

print

读取键盘输入

input: str = input('请输入:') print(str) raw_input 用法跟input相同,但是input函数能接收一个表达式作为输入,raw_input则不ok;另外,py3里面,已经没有这个函数了。

打开和关闭文件

打开: file = open('C:\\Users\liuhuichao\Pictures\demo.gif') print('文件名称 :'+file.name) print('是否已经关闭 :'+str(file.closed)) print('访问模式 :'+file.mode) file.close() #关闭 print('是否已经关闭 :'+str(file.closed)) 写入: file = open('C:\\Users\liuhuichao\Desktop\\test.txt', 'wb+') file.write(bytes('吃饭啦111111\n', 'utf-8')) file.close() 读取文件: file = open('C:\\Users\liuhuichao\Desktop\\test.txt', 'r') str = file.read() print(str) file.close()

文件定位

file = open('C:\\Users\liuhuichao\Desktop\\test.txt', 'r+') strfile = file.read(1) print(strfile) position = file.tell() #下一次的读写会发生在文件开头这么多字节之后。 print('当前位置:'+str(position)) file.seek(1, 0) print("当前位置:"+str(position)) #seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。 seek: 如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置。

重命名和删除文件

重命名:

import os os.rename('C:\\Users\liuhuichao\Desktop\\test.txt','C:\\Users\liuhuichao\Desktop\\test1.txt')

删除文件:

import os os.remove('C:\\Users\liuhuichao\Desktop\\test1.txt')
转载请注明原文地址: https://www.6miu.com/read-7404.html

最新回复(0)