纵有疾风起
人生不言弃

第2周-数据获取与表示

数据获取

本地数据获取

就是从本地读取数据,包括文件的打开读写和关闭。

打开和关闭文件

open()函数注意:

  1. 文件被打开后一定得记得关闭close()。否则可能会损害文件。所以尽量使用 with 。让python自己判断什么时候该关闭,并自己去关闭。
  2. open()后是一个对象,这个对象有read()方法与write()方法。
  3. 常用打开模式:
r 只能读 
r+ 可读可写,不会创建不存在的文件,从顶部开始写,会覆盖之前此位置的内容
w 只能写,覆盖整个原有文件(不要乱用),不存在则创建 
w+ 可读可写,如果文件存在,则覆盖整个文件,不存在则创建
a 只能写,从文件底部添加内容 不存在则创建 
a+ 可读可写 从文件顶部读取内容 从文件底部添加内容 不存在则创建

# 总结:从头开始用r+ ;从末尾开始用 a+ ;
想创建新的 用W+

如果我们在open文件后,没有进行任何读写,则默认r模式

with open ('pi.txt') as file_object :
    contents = file_object.read()
    print( contents )

逐行读取:

filename = 'pi.txt'
with open (filename) as file_object :
    for line in file_object:
        print (line)

文件写入

w模式:覆盖原有数据

filename = 'pi.txt'
with open (filename,'w') as file_object :
    file_object.write("i love you \n")
    file_object.write("i love you \n") # 加上\n可以一行一行的加入

a模式:添加新的内容,不会覆盖原有内容

filename = 'pi.txt'
with open (filename,'a') as file_object :
    file_object.write("i love you \n")
    file_object.write("i love you \n") # 加上\n可以一行一行的加入

数据存储json

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。

Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数:

json.dumps(): 对数据进行编码。
json.loads(): 对数据进行解码。

在json的编解码过程中,python 的原始类型与json类型会相互转换,具体的转化对照如下:

Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null

json.dumps 与 json.loads 实例

以下实例演示了 Python 数据结构转换为JSON:

#!/usr/bin/python3

import json

# Python 字典类型转换为 JSON 对象
data = { 'no' : 1, 'name' : 'Runoob', 'url' : 'http://www.runoob.com' }

json_str = json.dumps(data)
print ("Python 原始数据:", repr(data))
print ("JSON 对象:", json_str)

执行以上代码输出结果为:

Python 原始数据: {
  'url': 'http://www.runoob.com', 'no': 1, 'name': 'Runoob'}
JSON 对象: {
  "url": "http://www.runoob.com", "no": 1, "name": "Runoob"}

通过输出的结果可以看出,简单类型通过编码后跟其原始的repr()输出结果非常相似。
接着以上实例,我们可以将一个JSON编码的字符串转换回一个Python数据结构:

#!/usr/bin/python3

import json

# Python 字典类型转换为 JSON 对象
data1 = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}

json_str = json.dumps(data1)
print ("Python 原始数据:", repr(data1))
print ("JSON 对象:", json_str)

# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])

执行以上代码输出结果为:

Python 原始数据: {
  'name': 'Runoob', 'no': 1, 'url': 'http://www.runoob.com'}
JSON 对象: {
  "name": "Runoob", "no": 1, "url": "http://www.runoob.com"}
data2['name']:  Runoob
data2['url']:  http://www.runoob.com

如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。例如:

# 写入 JSON 数据
with open('data.json', 'w') as f:
    json.dump(data, f)

# 读取数据
with open('data.json', 'r') as f:
    data = json.load(f)

练习题:本地数据获取

问题如下:
     (1) 在任意位置创建一个.py文件,如'D:/编程练习/python练习/Week2_02.py'
     (2) 在D盘下创建一个文件Blowing in the wind.txt,即‘D:\Blowing in the wind.txt’
     其内容是:
How many roads must a man walk down
Before they call him a man
How many seas must a white dove sail
Before she sleeps in the sand
How many times must the cannon balls fly
Before they're forever banned
The answer my friend is blowing in the wind
The answer is blowing in the wind
     (3) 在文件头部插入歌名“Blowin’ in the wind”
     (4) 在歌名后插入歌手名“Bob Dylan”
     (5) 在文件末尾加上字符串“1962 by Warner Bros. Inc.”
     (6) 在屏幕上打印文件内容,最好加上自己的设计
     (7) 以上每一个要求均作为一个独立的步骤进行,即每次都重新打开并操作文件

代码如下

import os  
#Python的os模块提供了执行文件和目录处理操作的函数,例如重命名和删除文件。 
os.chdir('D:\\') #更改目录 

#------------------------------------------------------------------------- 
#创建一个文件,将歌词写入 
f1=open(r'Blowing in the wind.txt','w')  
f1.write('How many roads must a man walk down \n')  
f1.write('Before they call him a man \n')  
f1.write('How many seas must a white dove sail \n')  
f1.write('Before she sleeps in the sand \n')  
f1.write('How many times must the cannon balls fly \n')  
f1.write('Before they\'re forever banned \n')  
f1.write('The answer my friend is blowing in the wind \n')  
f1.write('The answer is blowing in the wind\n')  
f1.close()#文件使用后记得关闭 

#-------------------------------------------------------------------------- 
#在文件头部插入歌曲名 
# 因为R+模式,会替换掉原来位置的数据,所以写入的时候,必须再写一次。
f2=open(r'Blowing in the wind.txt','r+')#mode参数不能用'w+',这会清空原内容 
lyrics =f2.readlines()  
lyrics.insert(0,'Blowin\'in the wind\n')#在第一行添加歌曲名 
f2.seek(0,0)#将文件指针移动到文件开头处 
f2.writelines(lyrics)  
f2.close()  

#这是一种错误的写法,将歌词的第一行抹去了一部分 
#f2=open(r'Blowing in the wind.txt','r+') 
#f2.seek(0,0)#将文件指针移动到文件开头处 
#f2.write('Blowin’ in the wind\n') 
#f2.close() 

#-------------------------------------------------------------------------- 
#在歌名后插入歌手名(实现同上一步) 
f3=open(r'Blowing in the wind.txt','r+')#mode参数不能用'w+',这会清空原内容 
lyrics =f3.readlines()  
lyrics.insert(1,'——Bob Dylan\n')#在第一行添加歌手名 
f3.seek(0,0)#将文件指针移动到文件开头处 
f3.writelines(lyrics)  
f3.close()  

#-------------------------------------------------------------------------- 
#在文件末尾加上字符串“1962 by Warner Bros. Inc.” 
f4=open(r'Blowing in the wind.txt','a')#mode参数选择'a',代表追加模式. 
f4.write('1962 by Warner Bros. Inc.')#追加模式下,可以直接向文件末尾write内容 
f4.close()  

#-------------------------------------------------------------------------- 
#在屏幕上打印文件内容(最好加一些自己的格式设计) 
f5=open(r'Blowing in the wind.txt','r')  
article =f5.readlines()#读取文件内容 
#按照自己的方式显示 
for i in range(0,len(article)):  
    if 1<i<len(article)-1:  
        print('\t'+article[i])  
    else:  
        print('\t\t'+article[i])  
f5.close()  

网络数据获取

就是爬虫!专门有一个专题是讲解爬虫的,所以掠过不讲。

数据表示

序列

在python中, Python有6种序列 其中字符串 列表和元组是最常用的形式 。

只要是序列就可以用下标获取元素,从0到n-1

第2周-数据获取与表示插图

原文链接:https://lookme.blog.csdn.net/article/details/72865567

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

未经允许不得转载:起风网 » 第2周-数据获取与表示
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录