Python编程中的文件操作攻略
open函数 file object = open(file_name [,access_mode][,buffering])
File对象的属性 一个文件被打开后,你有一个file对象,你可以得到有关该文件的各种信息。 以下是和file对象相关的所有属性的列表: 如下实例: #!/usr/bin/python # -*- coding: UTF-8 -*- # 打开一个文件 fo = open("foo.txt","wb") print "Name of the file: ",fo.name print "Closed or not : ",fo.closed print "Opening mode : ",fo.mode print "Softspace flag : ",fo.softspace 以上实例输出结果: Name of the file: foo.txt Closed or not : False Opening mode : wb Softspace flag : 0 Close()方法 fileObject.close(); 例子: #!/usr/bin/python # -*- coding: UTF-8 -*- # 打开一个文件 fo = open("foo.txt",fo.name # 关闭打开的文件 fo.close() 以上实例输出结果: Name of the file: foo.txt
fileObject.write(string); 在这里,被传递的参数是要写入到已打开文件的内容。 例子: #!/usr/bin/python # -*- coding: UTF-8 -*- # 打开一个文件 fo = open("/tmp/foo.txt","wb") fo.write( "Python is a great language.nYeah its great!!n"); # 关闭打开的文件 fo.close() 上述方法会创建foo.txt文件,并将收到的内容写入该文件,并最终关闭文件。如果你打开这个文件,将看到以下内容: Python is a great language. Yeah its great!!
fileObject.read([count]);
#!/usr/bin/python # -*- coding: UTF-8 -*- # 打开一个文件 fo = open("/tmp/foo.txt","r+") str = fo.read(10); print "Read String is : ",str # 关闭打开的文件 fo.close() 以上实例输出结果: Read String is : Python is
#!/usr/bin/python # -*- coding: UTF-8 -*- # 打开一个文件 fo = open("/tmp/foo.txt",str # 查找当前位置 position = fo.tell(); print "Current file position : ",position # 把指针再次重新定位到文件开头 position = fo.seek(0,0); str = fo.read(10); print "Again read String is : ",str # 关闭打开的文件 fo.close() 以上实例输出结果: Read String is : Python is Current file position : 10 Again read String is : Python is
os.rename(current_file_name,new_file_name)
#!/usr/bin/python # -*- coding: UTF-8 -*- import os # 重命名文件test1.txt到test2.txt。 os.rename( "test1.txt","test2.txt" ) remove()方法 os.remove(file_name)
#!/usr/bin/python # -*- coding: UTF-8 -*- import os # 删除一个已经存在的文件test2.txt os.remove("text2.txt") (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |