Python之文件操作
浏览量:869
对文件操作流程
打开文件,得到文件句柄并赋值给一个变量
通过句柄对文件进行操作
关闭文件
现有文件如下:
Somehow, it seems the love I knew was always the most destructive kind 不知为何,我经历的爱情总是最具毁灭性的的那种 Yesterday when I was young 昨日当我年少轻狂 The taste of life was sweet 生命的滋味是甜的 As rain upon my tongue 就如舌尖上的雨露 I teased at life as if it were a foolish game 我戏弄生命 视其为愚蠢的游戏 The way the evening breeze 就如夜晚的微风 May tease the candle flame 逗弄蜡烛的火苗 The thousand dreams I dreamed 我曾千万次梦见 The splendid things I planned 那些我计划的绚丽蓝图 I always built to last on weak and shifting sand 但我总是将之建筑在易逝的流沙上 I lived by night and shunned the naked light of day 我夜夜笙歌 逃避白昼赤裸的阳光 And only now I see how the time ran away 事到如今我才看清岁月是如何匆匆流逝 Yesterday when I was young 昨日当我年少轻狂 So many lovely songs were waiting to be sung 有那么多甜美的曲儿等我歌唱 So many wild pleasures lay in store for me 有那么多肆意的快乐等我享受 And so much pain my eyes refused to see 还有那么多痛苦 我的双眼却视而不见 I ran so fast that time and youth at last ran out 我飞快地奔走 最终时光与青春消逝殆尽 I never stopped to think what life was all about 我从未停下脚步去思考生命的意义 And every conversation that I can now recall 如今回想起的所有对话 Concerned itself with me and nothing else at all 除了和我相关的 什么都记不得了 The game of love I played with arrogance and pride 我用自负和傲慢玩着爱情的游戏 And every flame I lit too quickly, quickly died 所有我点燃的火焰都熄灭得太快 The friends I made all somehow seemed to slip away 所有我交的朋友似乎都不知不觉地离开了 And only now I'm left alone to end the play, yeah 只剩我一个人在台上来结束这场闹剧 Oh, yesterday when I was young 噢 昨日当我年少轻狂 So many, many songs were waiting to be sung 有那么那么多甜美的曲儿等我歌唱 So many wild pleasures lay in store for me 有那么多肆意的快乐等我享受 And so much pain my eyes refused to see 还有那么多痛苦 我的双眼却视而不见 There are so many songs in me that won't be sung 我有太多歌曲永远不会被唱起 I feel the bitter taste of tears upon my tongue 我尝到了舌尖泪水的苦涩滋味 The time has come for me to pay for yesterday 终于到了付出代价的时间 为了昨日 When I was young 当我年少轻狂
操作:
f=open('lyrics','rb')
# with open('lyrics','rb') as f:
first_line=f.readline()
print(first_line)
data=f.read().decode("utf-8")
print(data)
f.close()打开文件的模式有:
r,只读模式(默认)。
w,只写模式。【不可读;不存在则创建;存在则删除内容;】
a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
r+,可读写文件。【可读;可写;可追加】
w+,写读
a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
rU
r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
rb
wb
ab
其他用法:
def close(self): # real signature unknown; restored from __doc__ """ Close the file. A closed file cannot be used for further I/O operations. close() may be called more than once without error. """ pass def fileno(self, *args, **kwargs): # real signature unknown """ Return the underlying file descriptor (an integer). """ pass def isatty(self, *args, **kwargs): # real signature unknown """ True if the file is connected to a TTY device. """ pass def read(self, size=-1): # known case of _io.FileIO.read """ 注意,不一定能全读回来 Read at most size bytes, returned as bytes. Only makes one system call, so less data may be returned than requested. In non-blocking mode, returns None if no data is available. Return an empty bytes object at EOF. """ return "" def readable(self, *args, **kwargs): # real signature unknown """ True if file was opened in a read mode. """ pass def readall(self, *args, **kwargs): # real signature unknown """ Read all data from the file, returned as bytes. In non-blocking mode, returns as much as is immediately available, or None if no data is available. Return an empty bytes object at EOF. """ pass def readinto(self): # real signature unknown; restored from __doc__ """ Same as RawIOBase.readinto(). """ pass #不要用,没人知道它是干嘛用的 def seek(self, *args, **kwargs): # real signature unknown """ Move to new file position and return the file position. Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values are SEEK_CUR or 1 (move relative to current position, positive or negative), and SEEK_END or 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). Note that not all file objects are seekable. """ pass def seekable(self, *args, **kwargs): # real signature unknown """ True if file supports random-access. """ pass def tell(self, *args, **kwargs): # real signature unknown """ Current file position. Can raise OSError for non seekable files. """ pass def truncate(self, *args, **kwargs): # real signature unknown """ Truncate the file to at most size bytes and return the truncated size. Size defaults to the current file position, as returned by tell(). The current file position is changed to the value of size. """ pass def writable(self, *args, **kwargs): # real signature unknown """ True if file was opened in a write mode. """ pass def write(self, *args, **kwargs): # real signature unknown """ Write bytes b to file, return number written. Only makes one system call, so not all of the data may be written. The number of bytes actually written is returned. In non-blocking mode, returns None if the write would block. """ pass
常用函数
file.close() #关闭文件,使不能再读写操作
file.flush() #刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。
f = open("lyrics", "wb")
print("文件名为: ", f.name)
# 刷新缓冲区
f.flush()
# 关闭文件
f.close()file.fileno() #返回一个整型的文件描述符(file descriptor FD 整型),可用于底层操作系统的 I/O 操作
f = open("lyrics", "wb")
print("文件名为: ", f.name)
fid = f.fileno()
print("文件描述符为: ", fid)
f.close()file.isatty() #方法检测文件是否连接到一个终端设备,如果是返回 True,否则返回 False。
f = open("lyrics", "wb")
print("文件名为: ", f.name)
ret = f.isatty()
print("返回值 : ", ret)
f.close()file.next () #方法在文件使用迭代器时会使用到,在循环中,next()方法会在每次循环中调用,该方法返回文件的下一行,如果到达结尾(EOF),则触发 StopIteration。
file.read() #方法用于从文件读取指定的字节数,如果未给定或为负则读取所有。
with open('lyrics','rb') as f:
data=f.read().decode("utf-8")
print(data)
f.close()file.readline() #用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。
f=open('lyrics','rb')
print("文件名为: ", f.name)
line = f.readline()
print("读取第一行 %s" % (line))
line = f.readline(5)
print("读取的字符串为: %s" % (line))
# 关闭文件
f.close()file.readlines() #用于读取所有行(直到结束符 EOF)并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比sizhint较大, 因为需要填充缓冲区。
如果碰到结束符 EOF 则返回空字符串。
first_line=f.readlines() first_line=f.readlines(2) print(first_line)
file.seek() #用于移动文件读取指针到指定位置。
f = open("lyrics", "rb+")
print("文件名为: ", f.name)
line = f.readline()
print("读取的数据为: %s" % (line))
# 重新设置文件读取指针到开头
f.seek(0, 0)
line = f.readline()
print("读取的数据为: %s" % (line))
# 关闭文件
f.close()fiel.tell() #返回文件的当前位置,即文件指针当前位置。
f = open("lyrics", "rb+")
print("文件名为: ", f.name)
line = f.readline()
print("读取的数据为: %s" % (line))
# 重新设置文件读取指针到开头
pos = f.tell()
print("当前位置: %d" % (pos))
f.close()file.truncate() #用于截断文件,如果指定了可选参数 size,则表示截断文件为 size 个字符。 如果没有指定 size,则从当前位置起截断;截断之后 size 后面的所有字符被删除。
f = open("lyrics", "rb+")
print("文件名为: ", f.name)
line = f.readline()
print("读取第一行: %s" % (line))
# 截断剩下的字符串
f.truncate()
# 尝试再次读取数据
line = f.readline()
print("读取数据: %s" % (line))
# 关闭文件
f.close()file.write() #用于向文件中写入指定字符串。在文件关闭前或缓冲区刷新前,字符串内容存储在缓冲区中,这时你在文件中是看不到写入的内容的。
f = open("test.txt", "w")
print("文件名为: ", f.name)
str = "zhangyang"
f.write( str )
# 关闭文件
f.close()file.writelines() #用于向文件中写入一序列的字符串。这一序列字符串可以是由迭代对象产生的,如一个字符串列表。换行需要制定换行符 \n。
f = open("test.txt", "w")
print("文件名为: ", f.name)
str = ["zhangyang1\n","zhangyang2"]
f.writelines( str )
# 关闭文件
f.close()with语句:
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open('log','r') as f:
...如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2:
pass重命名和删除文件
Python的os模块提供了帮你执行文件处理操作的方法,比如重命名和删除文件。要使用这个模块,你必须先导入它,然后可以调用相关的各种功能。
rename()方法:
rename()方法需要两个参数,当前的文件名和新文件名。
语法:
os.rename(current_file_name, new_file_name)
示例:
下例将重命名一个已经存在的文件test1.txt。
# 重命名文件test1.txt到test2.txt。
import os
os.rename('test1.txt','test2.txt')remove()方法
你可以用remove()方法删除文件,需要提供要删除的文件名作为参数。
import os
os.remove('test2.txt')Python里的目录
所有文件都包含在各个不同的目录下,不过Python也能轻松处理。os模块有许多方法能帮你创建,删除和更改目录。
mkdir()方法
可以使用os模块的mkdir()方法在当前目录下创建新的目录们。你需要提供一个包含了要创建的目录名称的参数。
语法:
os.mkdir("newdir")示例:
在当前目录下创建一个新目录test。
import os
os.mkdir('test')chdir()方法
可以用chdir()方法来改变当前的目录。chdir()方法需要的一个参数是你想设成当前目录的目录名称。
语法:
os.chdir("newdir")示例
import os
os.chdir('test')getcwd()方法:
getcwd()方法显示当前的工作目录。
语法:
os.getcwd()
示例:
import os print(os.getcwd())
rmdir()方法
rmdir()方法删除目录,目录名称以参数传递。在删除这个目录之前,它的所有内容应该先被清除。
语法:
os.rmdir('dirname')示例:
以下是删除" /tmp/test"目录的例子。目录的完全合规的名称必须被给出,否则会在当前目录下搜索该目录。
import os os.rmdir( "./test")

神回复
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。