python 目录 文件操作大全

  

目录操作 

1、得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()

>>> import os

>>> os.getcwd()

‘/home/jack‘

2、返回指定目录下的所有文件和目录名:os.listdir()

>>> os.listdir(‘/home/jack‘)

[‘.profile‘, ‘.bashrc‘, ‘test‘, ‘.bash_logout‘]

3、函数用来删除一个文件:os.remove()

#创建文件 >>> os.mknod("t1.txt")

#显示当前目录下的所有文件

>>> os.listdir(‘/home/jack‘)

[‘.profile‘, ‘.bashrc‘, ‘t1.txt‘, ‘test‘, ‘.bash_logout‘]

#删除文件

>>> os.remove("t1.txt")

>>> os.listdir(‘/home/jack‘)

[‘.profile‘, ‘.bashrc‘, ‘test‘, ‘.bash_logout‘]

4、删除多个目录:os.removedirs(r“c:\python”)

#创建多个目录

>>> os.makedirs("t1/t2")

>>> os.listdir(‘/home/jack‘)

[‘.profile‘, ‘.bashrc‘, ‘t1‘, ‘test‘, ‘.bash_logout‘]

>>> os.listdir(‘/home/jack/t1‘)

[‘t2‘]

#删除多个目录

>>> os.removedirs(r"/home/jack/t1/t2")

os.listdir(‘/home/jack‘)

[‘.profile‘, ‘.bashrc‘, ‘test‘, ‘.bash_logout‘]

5、检验给出的路径是否是一个文件:os.path.isfile()

>>> os.path.isfile(‘.bashrc‘)

True

>>> os.path.isfile(‘.bashrc1‘)

False

6、检验给出的路径是否是一个目录:os.path.isdir()

>>> os.path.isdir(‘/home/jack/test‘)

True

>>> os.path.isdir(‘/home/jack/test1‘)

False

7、判断是否是绝对路径:os.path.isabs()

>>> os.path.isabs(‘/home/jack/test‘)

True

>>> os.path.isabs(‘test‘)

False

8、检验给出的路径是否真地存:os.path.exists()

>>> os.path.exists(‘test‘)

True

>>> os.path.exists(‘test1‘)

False

9、返回一个路径的目录名和文件名:os.path.split()

>>> os.path.split(‘/home/jack/test‘)

(‘/home/jack‘, ‘test‘)

10、分离扩展名:os.path.splitext()

>>> os.path.splitext(‘/home/jack/test‘)

(‘/home/jack/test‘, ‘‘)

11、获取路径名:os.path.dirname()

>>> os.path.dirname(‘/home/jack/‘)

‘/home/jack‘

12、获取文件名:os.path.basename()

>>> os.mknod(‘a.txt‘)

>>> os.path.basename(‘/home/jack/a.txt‘)

‘a.txt‘

13、运行shell命令: os.system()

>>> os.system(‘ls -a‘)

.  ..  a.txt  .bash_logout  .bashrc  .profile  test

14、读取和设置环境变量:os.getenv() 与os.putenv()

getenv(key, default=None)

Get an environment variable, return None if it doesn‘t exist.

The optional second argument can specify an alternate default.

15、重命名:os.rename(old, new)

>>> import os

>>> os.listdir("/home/jack")

[‘.profile‘, ‘a.txt‘, ‘.bashrc‘, ‘.bash_history‘, ‘.ipython‘, ‘test‘, ‘.bash_logout‘]

>>> os.rename(‘a.txt‘,‘b.txt‘)

>>> os.listdir(‘/home/jack‘)

[‘.profile‘, ‘.bashrc‘, ‘.bash_history‘, ‘.ipython‘, ‘b.txt‘, ‘test‘, ‘.bash_logout‘]

16、创建多级目录:os.makedirs()

>>> os.makedirs(‘t1/t2‘)

>>> os.listdir(‘/home/jack‘)

[‘.profile‘, ‘.bashrc‘, ‘.bash_history‘, ‘.ipython‘, ‘t1‘, ‘b.txt‘, ‘test‘, ‘.bash_logout‘]

>>> os.listdir(‘/home/jack/t1‘)

[‘t2‘]

17、创建单个目录:os.mkdir()

>>> os.mkdir(‘abc‘)

>>> os.listdir(‘/home/jack‘)

[‘.profile‘, ‘abc‘, ‘.bashrc‘, ‘.bash_history‘, ‘.ipython‘, ‘t1‘, ‘b.txt‘, ‘test‘, ‘.bash_logout‘]

18、获取文件属性:os.stat(file)

>>> os.stat(‘b.txt‘)

posix.stat_result(st_mode=33152, st_ino=927137, st_dev=64769, st_nlink=1, st_uid=1001, st_gid=1001, st_size=0, st_atime=1510235921, st_mtime=1510235921, st_ctime=1510277660)

19、修改文件权限与时间戳:os.chmod(file)

参考博客:http://blog.csdn.net/wirelessqa/article/details/7974477

20、终止当前进程:os.exit()

21、获取文件大小:os.path.getsize(filename)

>>> os.path.getsize(‘b.txt‘)

0

文件操作

os.mknod("test.txt")             #创建空文件
fp = open("test.txt",w)          #直接打开一个文件,如果文件不存在则创建文件

r:以读方式打开文件,可读取文件信息。

w:以写方式打开文件,可向文件写入信息。如文件存在,则清空该文件,再写入新内容;如果文件不存在则创建

a:以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建

r+:以读写方式打开文件,可对文件进行读和写操作。

w+:消除文件内容,然后以读写方式打开文件。

a+:以读写方式打开文件,并把文件指针移到文件尾。

b:以二进制模式打开文件,而不是以文本模式。该模式只对Windows或Dos有效,类Unix的文件是用二进制模式进行操作的。

文件操作方法

常见文件操作方法:

方法

f.close() 关闭文件,记住用open()打开文件后一定要记得关闭它,否则会占用系统的可打开文件句柄数。

f.name()  获取文件名称

f.next()  返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。

f.flush() 刷新输出缓存,把缓冲区的内容写入硬盘

f.isatty()  如果文件是一个终端设备文件(Linux系统中),则返回True,否则返回False。

f.read([size])   读出文件,size为读取的长度,以byte为单位

f.readline([size])  读出一行信息,若定义了size,则读出一行的一部分

f.readlines([size])  读出所有行,也就是读出整个文件的信息。(把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分)

f.seek(offset[,where])

把文件指针移动到相对于where的offset位置。where为0表示文件开始处,这是默认值;1表示当前位置;2表示文件结尾。(注意:如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾)

f.tell()   获得文件指针位置,标记当前位置,以文件开头为原点

f.truncate([size])   把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。

f.write(string)  把string字符串写入文件,write()不会在str后加上一个换行符。

f.writelines(list)  把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。

文件操作模式举例

w  模式,如果没有文件,会自动创建

>>> os.listdir(‘/home/jack‘)
[‘.profile‘, ‘abc‘, ‘.bashrc‘, ‘.bash_history‘, ‘.ipython‘, ‘t1‘, ‘b.txt‘, ‘test‘, ‘.bash_logout‘]
>>> f1 = open(‘hello.txt‘,‘w‘)
>>> f1.write(‘hello world\n‘)
>>> f1.flush() #刷新输出缓存,把缓冲区的内容写入硬盘
>>> f1.close()

r 模式 只读模式

>>> f1 = open(‘hello.txt‘,‘r‘)
>>> print(f1.read())
hello world

r+ 模式  以读写方式打开文件,可对文件进行读和写操作。会清空原文件

>>> f1 = open(‘hello.txt‘,‘r+‘)
>>> f1.write(‘hello2 world\n‘)
>>> f1.close()
>>> f1 = open(‘hello.txt‘,‘r‘)
>>> print(f1.read())
hello2 world

w+  模式 消除文件内容,然后以读写方式打开文件。

>>> f1 = open(‘hello.txt‘,‘w+‘)
>>> f1.write(‘hello world ,hello world\n‘)
>>> f1.close()

>>> f1 = open(‘hello.txt‘,‘r‘)
>>> print(f1.read())
hello world ,hello world

a 模式 以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾)

如果文件不存在则创建,原有的文件内容保留

>>> f1 = open(‘hello.txt‘,‘a‘)
>>> f1.write(‘h2 h2\n‘)
>>> f1.close()
>>> f1 = open(‘hello.txt‘,‘r‘)
>>> print(f1.read())
hello world ,hello world
h2 h2

a+ 模式  以读写方式打开文件,并把文件指针移到文件尾。

>>> f1 = open(‘hello.txt‘,‘a+‘)
>>> f1.write(‘h3 h3 h3\n‘)
>>> f1.close()
>>> f1 = open(‘hello.txt‘,‘r‘)
>>> print(f1.read())
hello world ,hello world
h2 h2
h3 h3 h3

b :模式一般用于二进制文件的操作

文件读写方法

read # 读出所有文件,size为读取的长度,以byte为单位

readline #一行一行的读取

readlines #读出所有行,也就是读出整个文件的信息。(把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分)

f.write(string)  把string字符串写入文件,write()不会在str后加上一个换行符。

f.writelines(list)  把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。

时间: 2024-08-25 06:03:19

python 目录 文件操作大全的相关文章

Python文件操作大全

Python 编程文件操作大全   文件打开模式 打开模式 执行操作 'r' 以只读方式打开文件(默认) 'w' 以写入的方式打开文件,会覆盖已存在的文件 'x' 如果文件已经存在,使用此模式打开将引发异常 'a' 以写入模式打开,如果文件存在,则在末尾追加写入 'b' 以二进制模式打开文件 't' 以文本模式打开(默认) '+' 可读写模式(可添加到其他模式中使用) 'U' 通用换行符支持 文件对象方法 文件对象方法 执行操作 f.close() 关闭文件 f.read([size=-1])

python之文件操作-复制、剪切、删除等

下面是把sourceDir文件夹下的以.JPG结尾的文件全部复制到targetDir文件夹下: <span style="font-size:18px;">>>>import os >>> import os.path >>> import shutil >>> def copyFiles(sourceDir,targetDir): for files in os.listdir(sourceDir):

【整理】C#文件操作大全(SamWang)

[整理]C#文件操作大全(SamWang) 文件与文件夹操作主要用到以下几个类: 1.File类: 提供用于创建.复制.删除.移动和打开文件的静态方法,并协助创建 FileStream 对象. msdn:http://msdn.microsoft.com/zh-cn/library/system.io.file(v=VS.80).aspx 2.FileInfo类: 提供创建.复制.删除.移动和打开文件的实例方法,并且帮助创建 FileStream 对象 msdn:http://msdn.micr

jqm文件上传,上传图片,jqm的表单操作,jqm的ajax的使用,jqm文件操作大全,文件操作demo

最近在论坛中看到,在使用html5中上传图片或文件,出现各种问题.这一方面,我也一直没有做过,今天就抽出了一点时间来学习一下.现在的示例已经ok了,我就给大家分享一下,希望对大家有帮助. 好吧,我们先看看效果截图吧: 还行吧,来看页面代码: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <h

【转】c#文件操作大全(二)

61.文件夹移动到整合操作 FolderDialog aa = new FolderDialog();            aa.DisplayDialog();            if (aa.Path != "")            {                string filename = Path.GetFileName(%%1);                string path=(aa.Path.LastIndexOf("\")

【转】c#文件操作大全(一)

1.创建文件夹//using System.IO;Directory.CreateDirectory(%%1); 2.创建文件//using System.IO;File.Create(%%1); 3.删除文件//using System.IO;File.Delete(%%1); 4.删除文件夹//using System.IO;Directory.Delete(%%1); 5.删除一个目录下所有的文件夹//using System.IO;foreach (string dirStr in Di

C、C++文件操作大全

基于C的文件操作  在ANSI C中,对文件的操作分为两种方式,即流式文件操作和I/O文件操作,下面就分别介绍之. 一.流式文件操作  这种方式的文件操作有一个重要的结构FILE,FILE在stdio.h中定义如下: typedef struct {  int level; /* fill/empty level of buffer */  unsigned flags; /* File status flags */  char fd; /* File descriptor */  unsig

Python开发【第三章】:Python的文件操作

Python的文件操作 一.读取操作,3种读取方式的区别 #!/usr/bin/env python # -*- coding:utf-8 -*- #-Author-Lian info_file = open("here_we_are",encoding="utf-8") #默认读取模式 print(info_file) #不加参数,直接打印 #<_io.TextIOWrapper name='here_we_are' mode='r' encoding='u

python中文件操作的其他方法

前面介绍过Python中文件操作的一般方法,包括打开,写入,关闭.本文中介绍下python中关于文件操作的其他比较常用的一些方法. 首先创建一个文件poems: p=open('poems','r',encoding='utf-8')for i in p:print(i)结果如下: hello,everyone白日依山尽,黄河入海流.欲穷千里目,更上一层楼. 1.readline   #读取一行内容 p=open('poems','r',encoding='utf-8') print(p.rea