1.os模块

2.os.path 模块

3.实例

1. os模块

对文件系统的访问大多通过python的os模块实现,其中os 模块负责大部分的文件系统操作,包括删除/重命名文件,遍历目
录树,管理文件访问权限等。

2.os.path 模块,os.path完成一些针对路径名的操作,包括管理和操作文件路径名中的各个部分,获取文件或子目录信息,文件路径查询等操作。

3.实例

3.1 实例1:os模块和path模块接口使用

# encoding:utf-8
'''
Created on 2014-6-5 @author: Administrator
''' import os if __name__ == "__main__":
for tempdir in ('/tmp', r'c:\temp'):
if os.path.isdir(tempdir):
break else:
print "no temp directory is available"
tempdir = '' if tempdir:
os.chdir(tempdir)
cwd = os.getcwd()
print "***current temporary directory***"
print cwd print "***creating example directory..."
os.mkdir("example")
os.chdir("example")
cwd = os.getcwd()
print "***new working directory..."
print cwd print "***original directory listing:"
print os.listdir(cwd) print "***creating test file"
fobj = open("test", "w")
fobj.write("%s%s" % ("line1", os.linesep))
fobj.write("%s%s" % ("line2", os.linesep))
fobj.close() print "***updating directory listing:"
print os.listdir(cwd) print "***renaming test to filetest.txt"
os.rename("test", "filetest.txt") print "***updating directory listing:"
print os.listdir(cwd) path = os.path.join(cwd, os.listdir(cwd)[0])
print "***full file pathname:"
print path print "***(pathname,basename)="
print os.path.split(path)
print "***(filename,extension)="
print "***basename:", os.path.basename(path)
print os.path.splitext(os.path.basename(path)) print "***displaying file contents:"
fobj = open(path)
for eachline in fobj:
print eachline
fobj.close() print "***deleting test file"
os.remove(path)
print "***updating directory listing:"
print os.listdir(cwd) print "deleting test directory"
os.chdir(os.pardir)
os.rmdir("example") print "***Done!" name = raw_input(u"请输入名字:".encode("gbk"))
count=1;
for mytuple in os.walk(name, True):
print "%s:%s" %(count,mytuple[0])
count=count+1
print "%s:%s" %(count,mytuple[1])
count=count+1
print "%s:%s" %(count,mytuple[2])
count=count+1

3.2 实例2:目录文件深度遍历

"""文件目录深度遍历"""
def listdir(mydir, myfile):
global fmt
global filenum
lists = os.listdir(mydir) # 列出目录下的所有文件和目录
for line in lists:
filepath = os.path.join(mydir, line)
if os.path.isdir(filepath): # 如果filepath是目录,则再列出该目录下的所有文件
myfile.write(fmt + line.decode("gbk") + '\\' + '\n')
print fmt + line.decode("gbk") + '\\' + '\n',
filenum = filenum + 1 # 格式化输出目录
tmp = fmt
fmt = fmt + 4 * "-"
listdir(filepath, myfile)
fmt = tmp
else: # 如果filepath是文件,直接列出文件名
myfile.write(fmt + line.decode("gbk") + '\n') # 显示中文文件
print fmt + line.decode("gbk") + '\n',
filenum = filenum + 1 if __name__ == '__main__':
mydir = raw_input('please input the path:')
listfile = open('listfile.txt', 'w')
listfile.write(str(mydir).decode("gbk") + '\n')
listdir(str(mydir), listfile)
listfile.write('all the file num is ' + str(filenum))
listfile.close()

结果:

E:\KuGou
----Beyond - 不再犹豫.mp3
----Beyond - 喜欢你.mp3
----Beyond - 无尽空虚.mp3
----Beyond - 海阔天空.mp3
----Beyond - 谁伴我闯荡.mp3
----Beyond、黄家驹 - 海阔天空.m4a
----Cache\
--------3eb439fd4096a2b76ae8c1020f6c4007.kg!
----Lyric\
--------Beyond - 不再犹豫-2bcba2349cd515bf1110613c9a44acf9.krc
--------Beyond - 光辉岁月-4dc283c7ac7bd5d9bf9b72f167d4ec7d.krc
--------Beyond - 喜欢你-a48d906b0210cefc2d5d12353d3e7488.krc
--------Beyond - 无尽空虚-6ade279c2a7da6ce893e581ff22f7817.krc
--------Beyond - 海阔天空-f87ab6af058e9c5864a81a78e9f62967.krc
--------吴雨霏 - 今夜烟花灿烂-5810060a70bf1f583f92eb5d541d65e4.krc
--------周华健 - 让我欢喜让我忧-71c82c68ebab8ca9f97f460e7e8a58fa.krc
----Temp\
--------1d4182a7b02d9ea3185ddbbdece48473.kgtemp
--------2bcba2349cd515bf1110613c9a44acf9.kgtemp
--------4dc283c7ac7bd5d9bf9b72f167d4ec7d.kgtemp
----五月天 - 我不愿让你一个人.mp3
----刘德华 - 一起走过的日子.mp3
----刘德华 - 冰雨.mp3
----刘德华 - 北国之春.mp3
all the file num is 96

说明:以上结果有删减,主要是输出格式

3.3 实例3: os.walk 目录树

"""文件目录广度遍历"""
def walkdir(mydir,fileinfo,topdown=True):
for root, dirs, files in os.walk(mydir, topdown):
for name in files:
print(name)
fileinfo.write(name + '\n')
for name in dirs:
print(os.path.join(name))
fileinfo.write(os.path.join(root,name) + '\n') if __name__ == '__main__':
mydir = raw_input('please input the path:')
walkfile = open('walkfile.txt', 'w')
walkfile.write(str(mydir).decode("gbk") + '\n')
walkdir(str(mydir), walkfile)
walkfile.close()

说明:

1、raw_input 接收中文路径输入,在windows下需要保证eclipse控制台设置编码为GBK,具体设置为,右键单击需要运行的python文件,选择Run as-----Run configurations

设置Common编码为GBK,否则raw_input 结果为乱码

2. 保存文件路径名到文件中时,需要使用str.encode(“gbk”)的encode方式,同时保证写入文件路径名的文件格式为GBK,否则可能出现中文乱码

3.os.walk()调用的返回结果为一个对象,其中每个元素为一个三元组,三元组分别为(目录,子目录,目录下文件),(子目录,子目录下的子目录,子目录下的文件)……

【python】文件的输入和输出的更多相关文章

  1. Python 文件的输入与输出

    1. 文本文件的读写主要通过open()所构建的文件对象来实现.我们打开一个文件,并使用一个对象来表示该文件 , f = open(d,r) 其中d是文件名,r是模式 "r" 文件 ...

  2. C++:文件的输入和输出

    1.共同的打开文件方式: fin.open("test.txt",ios::binary) fout.open("test.txt",ios::binary) ...

  3. 雷林鹏分享:C# 文件的输入与输出

    C# 文件的输入与输出 一个 文件 是一个存储在磁盘中带有指定名称和目录路径的数据集合.当打开文件进行读写时,它变成一个 流. 从根本上说,流是通过通信路径传递的字节序列.有两个主要的流:输入流 和 ...

  4. 雷林鹏分享:Ruby 文件的输入与输出

    Ruby 文件的输入与输出 Ruby 提供了一整套 I/O 相关的方法,在内核(Kernel)模块中实现.所有的 I/O 方法派生自 IO 类. 类 IO 提供了所有基础的方法,比如 read. wr ...

  5. Python基础篇--输入与输出

    站长资讯平台:Python基础篇--输入与输出在任何语言中,输入和输出都是代码最基础的开始,so,先来聊一聊输入和输出输出输入END在任何语言中,输入和输出都是代码最基础的开始,so,先来聊一聊输入和 ...

  6. 从0开始的Python学习015输入与输出

    简介 在之前的编程中,我们的信息打印,数据的展示都是在控制台(命令行)直接输出的,信息都是一次性的没有办法复用和保存以便下次查看,今天我们将学习Python的输入输出,解决以上问题. 复习 得到输入用 ...

  7. 听翁恺老师mooc笔记(15)--文件的输入与输出

    <>重定向 如果使用标准的printf输出,有一个比较简便的方法,可以将程序的结果写入一个文件.使用<和>符号,将程序运行结果重定向到文件中去,具体使用到的代码如下: ./te ...

  8. C++_IO与文件4-简单文件的输入与输出

    通过键盘输入和屏幕输出被称为是控制台输入/输出: 更广义上讲控制台的输入/输出也是一种特殊的文件输入/输出: 当使用cin进行输入时,程序将输入视为一系列的字节,其中的每个字节都被解释成字符编码: 不 ...

  9. Python文件中将print的输出内容重定向到变量中

    有时候需要用到别人的代码, 但是又不想修改别人的文件, 想拿到输出的结果, 这时候就需要使用sys模块, 将print输出的内容重定向到变量中. Python调用sys模块中的sys.stdout, ...

随机推荐

  1. js生成有缩进的表格

    项目中用到用了两天时间想到的,记录下来,如有更好的方法,留言给我,谢谢! js做如下表格: json [{"id":302,"serviceId":15,&qu ...

  2. C++ string 转 char*

    string 转到 char* char name[20]; string sname=GatherName[n]; strcpy(name,sname.c_str());

  3. 18)Java八股文名词

      >VO:   value-object >DTO: Data Transform Object >DTD: Document Type Definition      文档类型定 ...

  4. Oracle 10g 之自动收集统计信息

    从10g开始,Oracle在建库后就默认创建了一个名为GATHER_STATS_JOB的定时任务,用于自动收集CBO的统计信息.这个自动任务默认情况下在工作日晚上10:00-6:00和周末全天开启. ...

  5. 使用@media做自适应

    @media (min-width: 768px){ //>=768的设备 }    @media (max-width: 1199){ //<=1199的设备 }

  6. django-url调度器-初级篇

    Django 遵从 MVC 模型,并将其特色化为 MTV 模型.模型的核心是通过用户访问的 url 来指向处理的函数,而函数处理后返回相应的结果.所以url决定了用户访问的入口,另外表单处理的提交地址 ...

  7. Python学习教程(learning Python)--1.4 Python数据处理基础

    本节主要讨论数据操作及运算符等基础知识,熟悉C语言相关知识的读者请跳过此节. 在高级语言编程过程中,有了数据以后通常要对数据进行相应的数据处理,加.减.乘.除等基本运算,不难理解. 在Python里 ...

  8. Android--调用系统的DownLoadManager去下载文件

    代码里面有详细的注释: /** * 该方法是调用了系统的下载管理器 */ public void downLoadApk(Context context,String url){ /** * 在这里返 ...

  9. linux新增一块硬盘加入原有分区

    原有硬盘空间已经不足,添加一块新硬盘,并且加入到原根目录下 查看新硬盘 1 2 fdisk -l Disk /dev/sdb: 240.1 GB, 240057409536 bytes 在新硬盘上创建 ...

  10. [原创]一个纯css实现兼容各种主流移动pc浏览器的时间轴

    废话不多说 Demo 高度完全的自适应 中心思想是table 和第二列行高的50%的上下绝对定位竖线 第一次用codepen less完全不能用啊 连node png之类的都是关键词会被去掉... 马 ...