python文件操作

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('
')
f.write('2')
f.close()

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

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

#在例2之后运行
f = open('D:spider\action.txt','a')
f.write('1')
f.write('
')
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('
')
    id = id + 1
f.close()

shoesItem.txt中:

 

原文地址:https://www.cnblogs.com/qilin20/p/12366896.html