代码改变世界

python文件操作

  默默不语  阅读(212)  评论(0编辑  收藏  举报

1.打开文件()

#参数1为文件路径
#参数2为打开方式
f = open('D:\spider\\shoesItem.txt','w')

2.向文件写入内容(参数必须为字符串)

f.write(content)

3.关闭文件流

f.close()

4.向文件写入内容时,每次换行输入

f = open('D:\spider\\action.txt','w')
f.write('1')
f.write('2')
f.close()

换行输入:

f = open('D:\spider\\action.txt','w')
f.write('1')
f.write('\n')
f.write('2')
f.close()

3.向文件中写入内容时不覆盖之前内容,即在文件末尾写入内容。(由上面的例子我们可以看到当程序再次运行时,之前文件中的内容就被覆盖了)

解决办法:将文件打开方式改为‘a’

#在例2之后运行
f = open('D:\spider\\action.txt','a')
f.write('1')
f.write('\n')
f.write('2')
f.close()

4.python向文件中写入数据时,文件中的文字全为乱码。

shoesItem.txt中:

 

解决方法:打开文件时设置编码方式为UTF-8

复制代码
id = 1
f = open('D:\spider\\shoesItem.txt','a',encoding='utf-8')
coon = pymysql.connect(user='root', password='root', host='127.0.0.1', port=3306, database='bishe_shoes',use_unicode=True, charset="utf8")
cursor = coon.cursor()
while id <= 139360:
    line = ""
    cursor.execute("select * from shoes where id = {}".format(id))
    shoes = cursor.fetchall()[0]
    print(shoes)
    line = str(shoes[0]) + '|' + shoes[1] + '|'+ str(shoes[2]) + '|' + shoes[3] + '|' + shoes[4] + '|'+ shoes[5] + '|' + shoes[6] + '|' + shoes[7]
    print(line)
    f.write(line)
    f.write('\n')
    id = id + 1
f.close()
复制代码

shoesItem.txt中:

 

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示