在Python中,你可以使用多种方法将数据保存到本地文件。以下是一些常见的方法:
1. 使用文本文件(.txt)
python
保存列表为.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文件
python
字典保存为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模块
python
使用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文件
python
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文件
python
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库)
python
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'`,以避免编码错误。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/51579.html