pyton入门 — 其他常用语法

实际的编程任务中常常会用到其他的.py文件,也会经常需要debug,所以针对这些,总结了一些常用的知识点。

1. 读取文件

下面是一段常用打开文件程序,使用到关键字 with ,函数 open ()read (),关键字 with 用于不再需要访问文件后将其关闭;

#这是用在xxxx.txt就放在程序所在文件夹内,即同一级文件中
with open('xxxx.txt') as file_object:
	contents = file_object.read()
	print(contents)
	
#用文件路径打开
file_path = '\xxxx\xxxxx\xxxx\filename.txt'
with open(file_path) as file_object:
	contents = file_object.read()
	print(contents)
  • 用 for 循环可以进行逐行读取:
with open('xxxx.txt') as file_object:
	for line in file_object:
	print(line.rstrip())
	
#文件内容仅在with中有用,故上下两端程序等效	
with open('xxxx.txt') as file_object:
	lines = file-object.readlines()
for line in lines:
	print(line.rstrip())

2. 写入文件

打开文件时一般有以下四种模式:只读(r),只写(w),读写(r+),追加模式(a),其他的模式后面慢慢了解;

with open('xxxx.txt','w') as file_object:
	file.object.write('fnhceuohcvoiwejpcje\n')
	file.object.write('qwefwefwef\n')
	file.object.write('fewgf\n')

3. Debug

使用打印进行debug是一种常见的方式,下面是在python中使用打印调试的方法:

try:
	code
except Error:
	error_info

4. 存储数据

使用 JSON格式 存储和分享数据;

  • 使用 json.dump() 进行存储
  • 使用 json.load() 进行读取
#需要导入json
import json

numbers = [2,3,4,5,6,7,8,9]
file_name = 'number.json'

#首先将列表写入文件内
with open(file_name, 'w' ) as file_obj:
	json.dump(numbers, file_obj)
	
#再
with open(file_name) as file_obj:
	numbers = json.load(file_obj)

print(numbers)

5. 代码测试工具

python标准库里面提供了一个用于测试的工具:unittest模块,后期再研究,先到这儿,回家睡觉~

你可能感兴趣的:(机器语言)