python读写文件和文件夹操作

2023-10-27  本文已影响0人  硅谷干货

一、打开文件

f=open('test.txt','r')
f.close()

此方法,文件使用结束后,用户必须关闭,因为文件对象会占用操作系统的资源。

with open('test.txt','r') as f:
      print(f.read)

此方法,引入了with语句来自动调用close()方法。

'r':读

'w':写

'a':追加

'r+' == r+w(可读可写,文件若不存在就报错(IOError))

'w+' == w+r(可读可写,文件若不存在就创建)

'a+' ==a+r(可追加可写,文件若不存在就创建)

二进制文件:

'rb'  'wb'  'ab'  'rb+'  'wb+'  'ab+'

二、读文件

with open('test.txt','r') as f:
      content=f.read()
with open('test.txt','r') as f:      
      line= f.readline()
      if line:
         print(line)
with open('test.txt','r') as f:      
      content=f.readlines()

注意:三种方法把每行末尾的\n也读进去了,需要手动删除

with open('test.txt') as f:            
       content= f.readlines()
       for I in range(len(content)) :
            content[I]=content[I].rstrip('\n')
################################
with open('test.txt') as f:
     arr=[]
     for lines in f.readlines():
         lines=lines.replace("\n","").split(",")
         arr.append(lines)

三、写文件

with open('test.txt','w') as f:            
        f.write('Hi!')
with open('test.txt','w') as f:            
        f.writelines(["1\n", "2\n", "3\n"])

四、文件夹操作

  1. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()
  2. 返回指定目录下的所有文件和目录名: os.listdir()
  3. 函数用来删除一个文件: os.remove()
  4. 删除多个目录:os.removedirs(r"c:\python")
  5. 检验给出的路径是否是一个文件:os.path.isfile()
  6. 检验给出的路径是否是一个目录:os.path.isdir()
  7. 判断是否是绝对路径:os.path.isabs()
  8. 检验给出的路径是否真地存: os.path.exists()
  9. 返回一个路径的目录名和文件名: os.path.split()

例子:

os.path.split('/home/swaroop/byte/code/poem.txt') 
结果:('/home/swaroop/byte/code', 'poem.txt')
  1. 分离扩展名:os.path.splitext()
  2. 获取路径名:os.path.dirname()
  3. 获取文件名:os.path.basename()
  4. 运行shell命令: os.system()
  5. 读取和设置环境变量: os.getenv() 与os.putenv()
  6. 给出当前平台使用的行终止符: os.linesep Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
  7. 指示你正在使用的平台:os.name 对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'
  8. 重命名:os.rename(old, new)
  9. 创建多级目录:os.makedirs(r"c:\python\test")
  10. 创建单个目录:os.mkdir("test")
  11. 获取文件属性:os.stat(file)
  12. 修改文件权限与时间戳:os.chmod(file)
  13. 终止当前进程:os.exit()
  14. 获取文件大小:os.path.getsize(filename)

五、目录操作

  1. 创建目录
os.mkdir("file")
  1. 复制文件:
shutil.copyfile("oldfile","newfile") #oldfile和newfile都只能是文件

shutil.copy("oldfile","newfile") #oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
  1. 复制文件夹:

  2. shutil.copytree("olddir","newdir") #olddir和newdir都只能是目录,且newdir必须不存在

  3. 重命名文件(目录)

os.rename("oldname","newname") #文件或目录都是使用这条命令
  1. 移动文件(目录)
shutil.move("oldpos","newpos")
  1. 删除文件
os.remove("file")
  1. 删除目录
os.rmdir("dir") #只能删除空目录

shutil.rmtree("dir") #空目录、有内容的目录都可以删
  1. 转换目录
os.chdir("path") #换路径
上一篇 下一篇

猜你喜欢

热点阅读