python 基本用法例子

import json

 

# Python 字典类型转换为 JSON 对象

data = {

'no' : 1,

'name' : 'W3CSchool',

'url' : 'http://www.w3cschool.cn'

}

json_str = json.dumps(data)

print ("Python 原始数据:", repr(data))

print ("JSON 对象:", json_str)

data2 = json.loads(json_str)

# 将 JSON 对象转换为 Python 字典

print ("data2['name']: ", data2['name'])

print ("data2['url']: ", data2['url'])

 

# 写入 JSON 数据

#with open('data.json', 'w') as f:

# json.dump(data, f)

# 读取数据

#with open('data.json', 'r') as f:

# data = json.load(f)

 

# 列表

word = "hello"

print(word[0:2])

print(word[2:4])

print(word[2:])

print(word[-2:])

print(word[:-2])

print(word[:])

print(len(word))

cube = [1,2,3]

# 数组添加元素

cube.append(4)

print(cube)

 

# 字典

from collections import OrderedDict

name2 = OrderedDict()

dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'}

print(dict)

dict["Sex"] = "male"

dict["son"] = {}

dict["son"]["name"] = "sonname"

dict["cube"] = cube

dictstr = json.dumps(dict)

print(dict["Name"])

print(json.dumps(cube))

 

# 遍历

for i in range(5):

print(i)

for i in cube :

print(i)

 

# 创建迭代器对象

list=[1,2,3,4]

it = iter(list)

for x in it:

print (x, end=" ")

print()

knights = {"gallahad:": "thepure", "robin:": "thebrave"}

for k, v in knights.items():

print(k, v)

 

# 文件路径

import os

import sys

curpath = os.path.dirname(os.path.abspath(sys.argv[0]))

test_path = os.path.abspath(sys.argv[0])#自己文件路径

 

print(os.path.abspath(test_path))

print(curpath)

print(test_path)

print(os.getcwd())

 

# 目录下的文件

os.chdir(curpath)

print(os.listdir())

#os.chdir(os.path.join(curpath, os.listdir()[1]))

#print(os.listdir())

print(os.path.isfile(os.listdir()[1]))#是不是文件

print(os.path.isdir(os.listdir()[1]))#是不是目录

print(os.path.abspath(os.listdir()[0]))#文件或者目录的绝对路径

print(os.path.basename(os.listdir()[0]))#文件或目录名

print(os.path.dirname(os.listdir()[0]))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值