python编程过程中会经常出现的一些使用问题_Python实际开发中经常用到和遇到的问题...

文件操作

读取大文件

with open('test.txt', 'r') as file:

while True:

line = file.readline()

if line:

print(line)

else:

break

多线程线程池

在实际开发中进程还是慎用的,但使用多线程要注意线程变量的问题,线程变量是共享的,因此操作一些文件要保证文件名是唯一的

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(6) as executor:

for each in get_card():

executor.submit(task, each)

批量移动

这样操作效率会高一些

import os, shutil

# 绝对路径

src_dir = os.path.abspath(r"C:\Users\Yaotc\Desktop\hi\train_2018")

dst_dir = os.path.abspath(r"C:\Users\Yaotc\Desktop\hi\data")

if not os.path.exists(dst_dir):

os.makedirs(dst_dir)

if os.path.exists(src_dir):

# root 所指的是当前正在遍历的这个文件夹的本身的地址

# dirs 是一个 list,内容是该文件夹中所有的目录的名字(不包括子目录)

# files 同样是 list, 内容是该文件夹中所有的文件(不包括子目录)

for root,dirs,files in os.walk(src_dir):

for file in files:

src_file = os.path.join(root, file)

shutil.copy(src_file, dst_dir)

print(src_file)

print('Done!')

序列化

json.dumps会变成unicode

json.dump(dic, ensure_ascii=False)

TypeError: a bytes-like object is required, not 'str'

存储数据的时候key若为单引号会报此错误

{"title": title, "avgScore": avgScore, "allCommentNum": allCommentNum, "address": address,"avgPrice": avgPrice}

计数器

文件移动

shutil

定时执行

想要定时执行脚本,而有不想安装太多依赖,可以使用shell的定时

# 查看定时任务

crontab -l

# 编辑定时任务

crontab -e

# 删除定时任务

crontab -r

# * * * * *

minute hour day month week

# * 表示任意 - 范围(2-6 == 2,3,4,5,6)

# , 取值(1,3,5,7) / (频率)

5 8-23/1 * * * /home/myshell.sh 8到23点每隔一个小时的第五分钟

shell传递变量

#!/bin/bash

a=1

b=2

sudo python test.py $a $b

参考文档

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值