python 爬虫 txt文档的读取和写入

python爬虫的各种存储方式之txt

简单下载一个图片:
from urllib import request
url="http://pic.netbian.com/uploads/allimg/180912/221007-15367614072cc2.jpg"
request.urlretrieve(url,"冰岛瀑布.jpg") #下载和存放

存入txt

判断目录,有则打开,没有新建

import os
if os.path.exists('D:\Python\代码\数据爬取'):
    os.chdir('D:\Python\代码\数据爬取')
else:
    os.mkdir('D:\Python\代码\数据爬取')
    os.chdir('D:\Python\代码\数据爬取')

1.写入txt,只能写入字符串

myfile = open('mytxt.txt','w',encoding='utf-8')
myfile.write('我在写入txt')
myfile.close()

#2.写入txt,追加内容
with open('mytxt.txt','a',encoding='utf-8') as file:
    file.write('\n123465')

#向mytxt.txt追加写入九九乘法表

with open('mytxt.txt','a',encoding='utf-8') as file:
   file.write('\n')
   for i in range(1,10):
       for j in range(1,i+1):
           num = str(j)+'x'+str(i)+'='+str(j*i)+'\t'
           file.write(str(num))
       file.write('\n')

#读取txt

with open('mytxt.txt','r',encoding='utf-8')as file:
    data = file.read()
print(data)

猜你喜欢

转载自blog.csdn.net/IT_arookie/article/details/82828606