首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python读写资料

2012-10-13 
python读写文件#--------------readwrite.py-----------------##--------------read and write file------

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转为stringf.close()#readlines()返回列表,每项为一行import pprintf = 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() 

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

热点排行