python第九周学习笔记

准备工作:os常用命令    自建一个文件夹,将当前目录修改为当前文件夹

import os
os.chdir(“D:\4.23”)

os.getcwd()
‘D:\4.23’

os.mkdir(“file_1”) #在当前目录建立子文件夹

os.mkdir(“file_2”)

os.rmdir(“file_2”) #删除文件夹

open(“my_file.txt”,‘w’) #w是只写,r是只读
<_io.TextIOWrapper name=‘my_file.txt’ mode=‘w’ encoding=‘cp936’>

open(“my_file_1.doc”,‘w’)
<_io.TextIOWrapper name=‘my_file_1.doc’ mode=‘w’ encoding=‘cp936’>

open(“hahaha.py”,‘w’)
<_io.TextIOWrapper name=‘hahaha.py’ mode=‘w’ encoding=‘cp936’>
查看该路径下的文件和文件夹

os.listdir()
[‘file_1’, ‘my_file.txt’, ‘my_file_1.doc’]

os.rename(“a.txt”,“b.py”) #改名

import os
os.chdir(“D:\4.23”)

os.mkdir(“big_data”)

FileExistsError Traceback (most recent call last)
in ()
----> 1 os.mkdir(“big_data”)

FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: ‘big_data’

os.chdir(“D:\4.23\big_data”)

open(“a.txt”,‘w’)
<_io.TextIOWrapper name=‘a.txt’ mode=‘w’ encoding=‘cp936’>

open(“b.doc”,‘w’)
<_io.TextIOWrapper name=‘b.doc’ mode=‘w’ encoding=‘cp936’>

open(“c.py”,‘w’)
<_io.TextIOWrapper name=‘c.py’ mode=‘w’ encoding=‘cp936’>

import os
for i in os.listdir():
os.rename(i,‘great_’+i)

for i in os.listdir():
os.rename(i,i - ‘great_’)

TypeError Traceback (most recent call last)
in ()
1 for i in os.listdir():
----> 2 os.rename(i,i - ‘great_’)

TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’

文件的打开与关闭

open(“my_file.txt”,‘w’).close()

open(“my_file_1.doc”,‘w’).close()

open(“hahaha.py”,‘w’).close()
‘r’ 只读
‘w’ 只写
‘x’ 创建写,文明不存在则创建,存在则返回异常
‘a’ 追加写模式,文件不存在则创建,存在则在原文件最后追加内容

‘b’ 二进制文件模式
‘t’ 文本文件模式,默认值
‘+’ 与r/w/x/a一同使用,在原功能基础上增加同时读写功能

f = open(‘a.txt’,‘x’)

f.close() #关闭文件

f=open(‘a.txt’,‘w’)

f.write(“Hello world!”)
12

f = open(‘a.txt’,‘r’)

f.read()
‘Hello world!’

f.seek(0) #自定光标的位置
0

f.tell() #返回光标的位置
0

f.read(3)
‘Hel’

f.close()

help(open)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值