Phython 3 笔记3 —— 类,库与文件的读写

类:

感觉类似于C++中的结构体

##定义类
class Mensch(object) :
    def __init__(self, name, age, salery) :
        self.name = name
        self.age = age
        self.salery = salery
    
    def say(self) :
        print(f"l'm {self.name} and {self.age}")

##使用类
fy = Mensch('fy', 18, 9999)
fy.say()

感觉类似C++的include<algorithm>

##导入库
import random #全部导入
import datetime
from urllib.parse import quote #部分导入

##调用库的例子
print(random.randint(0,100))
print(datetime.date.today())
print(quote('你好',safe = ''))

安装第三方库:

##在终端中输入,例如装requests库
pip install requests


#调用:获取网页源代码
import requests
html = requests.get('https://www.baidu.com').content.decode()
print(html)

读入txt文件:

##第一个引号里的是文件路径,第二个引号里windows用gbk,linux和macos用utf-8
with open('t.txt', encoding='gbk') as f:
    content = f.read() #全部读入
    content_list = f.readlines() #行读入,f只能读一次

print(content)
for i in content_list :
    print(i)

写入txt文件

## 'w' 是重写, 'a'是在原有的追加内容
with open('write.txt','w', encoding='gbk') as f :
    f.write('it is me')
    data = 'hello'
    f.writelines(data) #直接拼接
    f.writelines(''n'.join(data)) #带换行拼接

读入csv文件

import csv
with open('2.csv', encoding='gbk') as f:
    reader = csv.DictReader(f)
    for i in reader :
        print(i['name'])

写入csv文件

dict = [{'name':'tim','age':2,'grade':3},
        {'name':'fy','age':22,'grade':33}]
with open('write_2.csv',"w",encoding='gbk') as f:
    writer = csv.DictWriter(f,fieldnames=['name','age','grade'])
    writer.writeheader()
    writer.writerows(dict)

 

posted @ 2018-03-03 17:38  Frank的成长之路  阅读(306)  评论(0编辑  收藏  举报