Python读写文件操作

一、python读文件操作

首先定义文件路径,例如:

DirPath = "./title.csv"

然后就可以使用with open方法读文件内容了,例如:

with open(DirPath,'r',encoding="utf-8") as f:
    datas = f.readlines()
    for data in datas:
        list = data.split(",")
        if list.__len__() == 3:
           id,title,imdb_index = list
        else:
            continue

二、python写文件操作

第一步和读文件同理定义文件路径:但是这里改成’w’

with open("./nanhu.csv",'w',encoding="utf-8") as t:

如果你想直接写字符串那么:

t.write('Hello, world!')
	#换行
	t.write('\r\n')
	##将两者拼在一起即可
	t.write('Hello, world!\r\n')

不过这里更建议使用pandas的方法:

name = ["num", "date1", "place", "id", "name", "phone","abc"]
        test = pd.DataFrame(columns=name,data=result)
        test.to_csv("./nanhu.csv")

这里先定义输出文件的title,然后将数据放在result中进行赋值。结果就会直接输出成 .csv 格式的文件了~