`

python读写文件

 
阅读更多
#--------------readwrite.py-----------------#
#--------------read and write file----------#
#write(string)
f = open("readwrite.txt",'w')
f.write("Welcome to this file\nThere is nothing here except\nThis stupid haiku\n")
f.close()

#writelines(list)
f = open("readwrite.txt")#默认为读
lines = f.readlines()
f.close()

lines[0] = "#-----writelines(list)-------#\nWelcome to this file\n"
f = open("readwrite.txt",'a')#a模式在原文件上继续添加
f.writelines(lines)
f.close()

#read(n)读取前n个字符
f = open("readwrite.txt","r")
print "#-------------------------read(n)----------------------------#"
print f.read(4)
f.close()

#readline()按行读取
f = open("readwrite.txt")
print "#-------------------------readline()----------------------------#"
for i in range(3):
    print str(i) + ": " + f.readline() #str(i)将object转为string
f.close()

#readlines()返回列表,每项为一行
import pprint
f = open("readwrite.txt")
l = f.readlines()#返回列表
print l#输出列表
print "---------------------------------------"
pprint.pprint(l)#每项为一行显示,而且是文件对象自动关闭的方法,所以无f.close()

         

 

 

另一个读写实例

#----------picknames.py----------"
import os
#os.getcwd()返回一个表示当前工作目录的字符串,若在D:\python目录下执行此函数则返回结果"D:\PYTHON"
#os.listdir()返回一个参数所指定目录的所有文件名字符串的列表,若目录内有文件file1.rm,flie2.rm,file3.rm则返回结果['file1.rm','file2.rm','file3.rm']
filenames = os.listdir(os.getcwd())
for name in filenames:
    filenames[filenames.index(name)] = name[:-3]#将每项名字去掉后三位
#open为内建函数,w表示写模式,该语句新建names.txt可以进行写操作
out = open("names.txt","w")
for name in filenames:
    out.write(name + "\n")#开始写内容
out.close()

#读文件
f = open("names.txt","r")
#读取前四个字符
print f.read(4)
#读取剩下的字符
print f.read()

 

 

分享到:
评论
1 楼 wanglei2999 2012-07-13  
#----------picknames.py----------" 
import os 
#os.getcwd()返回一个表示当前工作目录的字符串,若在D:\python目录下执行此函数则返回结果"D:\PYTHON" 
#os.listdir()返回一个参数所指定目录的所有文件名字符串的列表,若目录内有文件file1.rm,flie2.rm,file3.rm则返回结果['file1.rm','file2.rm','file3.rm'] 
filenames = os.listdir(os.getcwd()) 
for name in filenames: 
    filenames[filenames.index(name)] = name[:-3]#将每项名字去掉后三位 
#open为内建函数,w表示写模式,该语句新建names.txt可以进行写操作 
out = open("names.txt","w") 
for name in filenames: 
    out.write(name + "\n")#开始写内容 
out.close() 

如果文件名字是中文,会有乱码问题,请问楼主如何处理?谢谢

相关推荐

Global site tag (gtag.js) - Google Analytics