python 读写文件

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


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

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

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

os.makedirs(路径) 建立目录spa

os.getcwd()  获取当前目录code

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

相对路径和绝对路径:ip

• 调用 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'

检查路径有效性:get

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

二、文件读写过程

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

  • 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()

三、遍历目录

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('')
相关文章
相关标签/搜索