python保存数据到本地文件的方法

yipeiwu_com6年前Python基础

1、保存列表为.txt文件

#1/list写入txt

ipTable = ['158.59.194.213', '18.9.14.13', '58.59.14.21'] 
fileObject = open('sampleList.txt', 'w') 
for ip in ipTable: 
 fileObject.write(ip) 
 fileObject.write('\n') 
fileObject.close() 

2、字典保存

#2/dict写入json
import json

dictObj = { 
 'andy':{ 
  'age': 23, 
  'city': 'shanghai', 
  'skill': 'python' 
 }, 
 'william': { 
  'age': 33, 
  'city': 'hangzhou', 
  'skill': 'js' 
 } 
} 

jsObj = json.dumps(dictObj) 

fileObject = open('jsonFile.json', 'w') 
fileObject.write(jsObj) 
fileObject.close() 

以上这篇python保存数据到本地文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

5个很好的Python面试题问题答案及分析

本文的主要内容是向大家分享几个Python面试中的T题目,同时给出了答案并对其进行分析,具体如下。 本文的原文是5 Great Python Interview Questions,同时...

python+pygame实现坦克大战

python+pygame实现坦克大战

本文实例为大家分享了python+pygame实现坦克大战的具体代码,供大家参考,具体内容如下 一、首先导入pygame库 二、源码分享 #coding=utf-8 impo...

python使用scrapy解析js示例

复制代码 代码如下:from selenium import selenium class MySpider(CrawlSpider):    name =...

python远程连接MySQL数据库

本文实例为大家分享了python远程连接MySQL数据库的具体代码,供大家参考,具体内容如下 连接数据库 这里默认大家都已经配置安装好 MySQL 和 Python 的MySQL 模块,...

python实现控制电脑鼠标和键盘,登录QQ的方法示例

本文实例讲述了python实现控制电脑鼠标和键盘,登录QQ的方法。分享给大家供大家参考,具体如下: import os from pynput.mouse import Button...