在Python中保存文件到本地,你可以使用 `with open` 语句,配合不同的模式(如 'w' 表示写入,'r' 表示读取等)和编码(如 'utf-8')来操作文件。以下是一些基本的示例:
1. 保存列表为.txt文件:
```python
ipTable = ['158.59.194.213', '18.9.14.13', '58.59.14.21']
with open('sampleList.txt', 'w', encoding='utf-8') as fileObject:
for ip in ipTable:
fileObject.write(ip + '\n')
2. 保存字典为.json文件:
```python
import 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 fileObject:
json.dump(dictObj, fileObject, ensure_ascii=False)
3. 保存数据框为CSV或Excel文件:
```python
import pandas as pd
df = pd.DataFrame(np.random.randn(10,4))
df.to_csv('PandasNumpy.csv')
df.to_excel('PandasNumpy.xlsx', engine='openpyxl')
4. 使用pickle模块保存和加载数据:
```python
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)
使用 `with open` 语句的好处是文件会在代码块执行完毕后自动关闭,无需手动调用 `fileObject.close()`。