Python 文件I/O
讲述基本的的I/O函数,更多函数请参考Python标准文档。
文件操作
打开和关闭文件
raw_input()函数
str = raw_input(“请输入:”);
print “你输入的内容是: “, str
open() 方法
说明:open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写,若没有文件,则新建一个文件。
file object = open(file_name [, access_mode][, buffering])
DemoExample:
my_file = open("output.txt","r+")
Close() 方法
说明:ile 对象的 close()方法刷新缓冲区里任何还没写入的信息,并关闭该文件.
fileObject.close();
DemoExample:
# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name
# 关闭打开的文件
fo.close()
读写文件
read()方法
read()方法从一个打开的文件中读取一个字符串。Python字符串可以是二进制数据,而不是仅仅是文字。
fileObject.read([count]);
DemoExample:
# 打开一个文件
fo = open("foo.txt", "r")
str = f0.read()
print str
# 关闭打开的文件
fo.close()
write()方法
说明: write()方法可将任何字符串写入一个打开的文件。Python字符串可以是二进制数据,而不是仅仅是文字。write()方法不会在字符串的结尾添加换行符('\n')。
fileObject.write(string);
DemoExample:
# 打开一个文件
fo = open("foo.txt", "wb")
fo.write( "www.runoob.com!\nVery good site!\n");
# 关闭打开的文件
fo.close()
重命名和删除文件
Python的os模块提供了帮你执行文件处理操作的方法,比如重命名和删除文件。
rename()方法:rename()方法需要两个参数,当前的文件名和新文件名。
rename()方法
os.rename(current_file_name, new_file_name)
DemoExample:
import os
# 打开一个文件
f = open("output4.txt", "w")
os.rename( "output4.txt", "output5.txt" )
# 关闭打开的文件
fo.close()
remove()方法
可以用remove()方法删除文件,需要提供要删除的文件名作为参数。
os.remove(file_name)
DemoExample:
import os
# 删除一个已经存在的文件test2.txt
os.remove("test2.txt")
文件夹操作
getcwd()方法
os.getcwd()
DemoExample:
import os
# 给出当前的目录
os.getcwd()
输出-> E:\PythonCode
mkdir()方法
可以使用os模块的mkdir()方法在当前目录下创建新的目录,如果已有目录,则会报错。
os.mkdir(“newdir”)
DemoExample:
import os
os.mkdir("newdir")
目录变化-> E:\PythonCode\newdir
chdir()方法
可以用chdir()方法来改变当前的目录。chdir()方法需要的一个参数是你想设成当前目录的目录名称。
os.chdir(“newdir”)
DemoExample:
import os
# 将当前目录改为"/home/newdir"
os.chdir ("E:\\PythonCode\\newdir")
rmdir()方法
rmdir()方法删除目录,目录名称以参数传递。在删除这个目录之前,它的所有内容应该先被清除。
os.rmdir(‘dirname’)
DemoExample:
import os
# 删除"E:\\PythonCode\\newdir1"目录
os.rmdir( "E:\\PythonCode\\newdir1")