python常用代码
换卡
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
打乱数据
train_data = pd.read_csv('./train_preprocessed.csv')
train_data = train_data.sample(frac=1).reset_index(drop=True)
限制cpu数目
torch.set_num_threads(3)
读入json(或格式相同的txt)
情形1:字典没有逗号隔开
方法一:
with open(tmp_file, "r", encoding='utf-8') as f:
tmp_list = [json.loads(line) for line in f.readlines()]
方法二:
data_list = [json.loads(line) for line in open(file_name)]
这样读入的tmp_list长度为5,每个元素都是个字典
将这个文件后缀从txt换成json,代码无需改动,效果不变
情形2:字典以逗号隔开,放在一整个list中
with open(tmp_file, "r", encoding='utf-8') as f:
tmp_list = json.load(f)
这样读入的tmp_list长度也是5,每个元素都是个字典
将这个文件后缀从txt换成json,代码无需改动,效果不变
写入json (或格式相同的txt)
情形1:字典没有逗号隔开
# ans是保存待写入内容的list
with open(filename, 'w', encoding='utf-8') as f:
for line in ans:
f.write(line+"\n")
f.flush()
情形2:字典以逗号隔开,放在一整个list中
with open(dataset_path + 'filename.json', 'w') as f:
json.dump(tmp_list, f, ensure_ascii=False, indent=4)
上述这样就能将元素是字典的list写回文件中
将文件后缀从json换成txt,效果等价
读入jsonl
情形:字典没有逗号隔开
with jsonlines.open(input_file, "r") as f:
for i, obj in enumerate(f):
# do something
写入jsonl
情形:字典没有逗号隔开
with jsonlines.open(output_file, 'w') as writer:
for d in data_list:
writer.write(d)
写csv文件
myfile = open(r'test1.txt','w')
#‘w’是写入模式,会直接清空test1.txt文件中的内容,重新写入。 如果你不想清空原来内容, 就要使用‘a’模式,意为追加
myfile.write('从你的全世界路过')
myfile.close()
使用with:
with open(r'test.txt','a') as myfile:
myfile.write('你好')
图片和音频要使用wb格式
例:写入下列内容到detaillist.csv中
import csv #引入csv模块
#获取用户输入的贷款总额与贷款年限
total_loan = int(input('请输入贷款总额(贷款总额为整数):'))
total_loan_year = int(input('银行贷款基准利率:1年期6.56%;2年期6.65%;3年期6.65%;4年期6.90%;5年期6.90%;请选择还款年限,输入数字即可:'))
#年利率
year_rate = 0
if total_loan_year==1: #1年期
year_rate = 0.0656
elif 1<total_loan_year<=3: #2年期、3年期
year_rate = 0.0665
elif 3<total_loan_year<=5: #4年期、5年期
year_rate = 0.069
#月利率
month_rate = year_rate/12
#还款月数
loan_month = total_loan_year*12
#累计还款总额
sum_money = 0
#调用open()方法,文件名是detaillist.csv,追加模式"a", 文件名在代码中称为listfile
with open("detaillist.csv","a",newline='',encoding='GBK') as listfile:
#使用csv.writer()函数创建writer对象,用于写入
writer = csv.writer(listfile, dialect='excel')
#列表头部第一行的字段
header = ['期次','偿还本息(元)','偿还本金(元)','偿还利息(元)']
# 使用writer对象写入表头
writer.writerow(header)
#循环计算所有月份的数据
for i in range(1, loan_month + 1):
print("第" + str(i) + "月还款情况")
#每月还款总额
month_money = (total_loan * month_rate * (1 + month_rate) ** loan_month) / (
(1 + month_rate) ** loan_month - 1)
#每月偿还本金
month_capital = total_loan * month_rate * ((1 + month_rate) ** (i - 1)) / ((1 + month_rate) ** loan_month - 1)
#每月偿还利息
month_interest = month_money - month_capital
#累计还款总额计算
sum_money = sum_money+month_money
print(month_money)
print(month_capital)
print(month_interest)
writer.writerow([i, month_money, month_capital, month_interest]) #期次可改为str(i)+"期" 若要求四舍五入到两位,则为round(month_money,2)
sum_interest = sum_money - total_loan
print(sum_money)
print(total_loan)
print(sum_interest)
读csv文件
myfile = open(r'test.txt','r')
myfilecontent = myfile.read()
print(myfilecontent)
myfile.close()