Python——文件IO

打印到屏幕

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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值