在Python中,你可以使用多种方法将数据保存到本地文件。以下是一些常见的方法:
1. 使用文本文件(.txt)
保存列表为.txt文件
ipTable = ['158.59.194.213', '18.9.14.13', '58.59.14.21']
with open('sampleList.txt', 'w', encoding='utf-8') as file:
for ip in ipTable:
file.write(ip + '\n')
2. 使用JSON文件
字典保存为JSON文件
dictObj = {'andy': {'age': 23, 'city': 'shanghai', 'skill': 'python'},
'william': {'age': 33, 'city': 'hangzhou', 'skill': 'js'}}
with open('jsonFile.json', 'w', encoding='utf-8') as file:
json.dump(dictObj, file, ensure_ascii=False, indent=2)
3. 使用Pickle模块
使用pickle模块保存数据
import pickle
data1 = {'a': [1, 2.0, 3, 4+6j], 'b': ('string', u'Unicode string'), 'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)
with open('data.pkl', 'wb') as output:
pickle.dump(data1, output)
pickle.dump(selfref_list, output, -1)
4. 使用CSV文件
import csv
data = [['name', 'gender', 'birthday'],
['Bob', 'male', '1992-10-18'],
['Selina', 'female', '1995-10-18']]
with open('data.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)
5. 使用Excel文件
import openpyxl
data = [['name', 'gender', 'birthday'],
['Bob', 'male', '1992-10-18'],
['Selina', 'female', '1995-10-18']]
wb = openpyxl.Workbook()
ws = wb.active
ws.append(data)
for row in data[1:]:
ws.append(row)
wb.save('data.xlsx')
6. 使用HTML文件(使用urllib库)
import urllib.request
response = urllib.request.urlopen('http://example.com')
html = response.read()
with open('example.html', 'wb') as file:
file.write(html)
以上是保存数据到本地文件的一些基本方法。你可以根据数据类型和需求选择合适的方法。需要注意的是,在处理文本数据时,通常需要指定文件的编码方式,如`encoding='utf-8'`,以避免编码错误。