我想以时间戳命名照片的文件名,但是3行和5行代码不知道怎么改(刚学编程)

我想在树莓派上以时间戳命名照片的文件名,但是3行和5行代码不知道怎么改(本人刚学编程)

(部分代码)
1 while True:
2 #filepath = input('input the file: ')
3 os.system("raspistill -o image2.jpg")
4 time.sleep(1)
5 filepath = 'image2.jpg'
6 fhead = struct.pack(b'128sl', bytes(os.path.basename(filepath).encode('utf-8')), os.stat(filepath).st_size)
7 s.send(fhead)
8 print('client filepath: {0}'.format(filepath))

尝试过
3 os.system("raspistill -o {time.ctime{}.jpg")
5 filepath = '{time.ctime{}.jpg'
树莓派可以拍照,但第五行报错是找不文件(文件名是第五行的时间)
应该是树莓派拍照需要时间,所以第3行第5行时间不一样

请问应该怎么改

第5行改为


# 1.时间戳命名
name = int(time.time())

# 2. 你的代码里面第三行应该是拍照,且照片的名字是 默认的 image2.jpg .可以用 os.rename()
import os
os.rename("旧文件名字","新文件名字")
# 也就是,注意路径问题
os.rename("image2.jpg",str(name)+".jpg")

时间戳应该是time.time()哦

while True:
    #filepath = input('input the file: ')
    path_name = time.time()
    os.system(f"raspistill -o {path_name}.jpg")
    time.sleep(1)
    fhead = struct.pack(b'128sl', bytes(os.path.basename(path_name).encode('utf-8')), os.stat(path_name).st_size)
    s.send(fhead)
    print('client filepath: {0}'.format(filepath))
  1. 你都sleep了,时间肯定不一样了,所以你要提前生成固定的文件名
  2. time.ctime()有特殊字符的原因会有问题,要用时间戳可以用print(int(time.time()))
  3. 可以用更友好的方式
import os
from datetime import datetime
import time

fileName = f"{datetime.now().strftime('%Y-%M-%d-%H-%M-%S')}.txt"
os.system(f"echo 'test' >> {fileName}")

time.sleep(1)
with open(fileName) as file:
    print(file.readlines())

没有日志都可以解决问题的吗?

1 while True:
2 #filepath = input('input the file: ')
3 os.system("raspistill -o image2.jpg")
4 time.sleep(1)
5 filepath = 'image2.jpg'
6 fhead = struct.pack(b'128sl', bytes(os.path.basename(filepath).encode('utf-8')), os.stat(filepath).st_size)
7 s.send(fhead)
8 print('client filepath: {0}'.format(filepath))
尝试过
3 os.system("raspistill -o {time.ctime{}.jpg")
5 filepath = '{time.ctime{}.jpg'

只看代码第五行,一点毛病都没有,怎么会说运行不了呢?
你的环境是树莓派,这个要看具体的树莓派版本,还有 里面所安装的python环境版本;
同时,还依赖你所操作的系统;
而这些,是需要你的报错日志来判断的哈;

前面的回答,没有日志,都是瞎猜

参考一下

这篇文章很适合你,希望对你有所帮助
https://blog.csdn.net/loveSIYU/article/details/114604473

看看log 看看有没有报错之类的