python 读写文件

1、文件及其路径相关函数


os.path.dirname(path)  返回路径中的目录路径

os.path.join(路径参数)   返回完整的路径

os.path.split(path)   分割目录路径和文件名,返回这两个组成的元组
os.path.getsize(path)  获取文件大小,返回字节数
os.listdir(path)  将返回文件名字符串的列表,即目录下所有文件

os.makedirs(路径) 创建目录

os.getcwd()  获取当前目录

os.chdir(路径)  切换目录,当目录不存在时会报 FileNotFoundError 异常

 

myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filename in myFiles:
    print(os.path.join('C:\\Users\\asweigart', filename))
#C:\Users\asweigart\accounts.txt
#C:\Users\asweigart\details.csv
#C:\Users\asweigart\invite.docx

相对路径和绝对路径:

• 调用 os.path.abspath(path)将返回参数的绝对路径的字符串。这是将相对路径转
换为绝对路径的简便方法。
• 调用 os.path.isabs(path),如果参数是一个绝对路径,就返回 True,如果参数是
一个相对路径,就返回 False。
• 调用 os.path.relpath(path, start)将返回从 start 路径到 path 的相对路径的字符串。
如果没有提供 start,就使用当前工作目录作为开始路径

os.path.abspath('.')
#'C:\\Python34'
os.path.abspath('.\\Scripts')
#'C:\\Python34\\Scripts'
os.path.isabs('.')
#False
os.path.isabs(os.path.abspath('.'))
#True

os.path.relpath('C:\\Windows', 'C:\\')
#'Windows'
os.path.relpath('C:\\Windows', 'C:\\spam\\eggs')
#'..\\..\\Windows'
os.getcwd()
#'C:\\Python34'

检查路径有效性:

os.path.exists('C:\\Windows')   #路径是否存在
#True
os.path.exists('C:\\some_made_up_folder')
#False
os.path.isdir('C:\\Windows\\System32') 是否存在并且是目录
#True
os.path.isfile('C:\\Windows\\System32') 是否存在并且是文件
#False
os.path.isdir('C:\\Windows\\System32\\calc.exe')
#False
os.path.isfile('C:\\Windows\\System32\\calc.exe')
#True

2、文件读写过程

在 Python 中, 读写文件有 3 个步骤:

  • 1. 调用 open()函数, 返回一个 File 对象。
  • 2.调用 File 对象的 read()或 write()方法。
  • 3.调用 File 对象的 close()方法,关闭该文件。
     
sonnetFile = open('001.txt','w')
content = '''When, in disgrace with fortune and men's eyes,
             I all alone beweep my outcast state,
             And trouble deaf heaven with my bootless cries,
             And look upon myself and curse my fate,'''

sonnetFile.write(content)
sonnetFile.close()

with open('001.txt','r') as f:
    print f.readlines()

3、遍历目录

os.walk()函数被传入一个字符串值,即一个文件夹的路径。os.walk()在循环的每次迭代中,返回 3 个值:
1. 当前文件夹名称的字符串。
2.当前文件夹中子文件夹的字符串的列表。
3. 当前文件夹中文件的字符串的列表。

import os
for folderName, subfolders, filenames in os.walk('E:\\pyscripts'):
    print('The current folder is ' + folderName)
    for subfolder in subfolders:
        print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
    for filename in filenames:
        print('FILE INSIDE ' + folderName + ': '+ filename)
    print('')

 

转载于:https://my.oschina.net/u/2440318/blog/843318

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值