python - How do I add an if and else statement to python?
问题描述
I'm currently learning python and I'm trying to add if/else statements.
For example, I have this script that changes the file names within a directory to something else:
import os
#changes directory
os.chdir('/home/Documents/agreements')
for f in os.listdir('/home/rachellegarcia/Documents/agreements'):
f_name, f_ext = os.path.splitext(f)
f_patient, f_conf, f_agmt, f_email = f_name.split('_')
f_agmt_type, f_agmt_staff = f_agmt.split('-')
#sets the new name
new_name = '{}-{}{}'.format(f_agmt_staff, f_email, f_ext)
#renames the file
os.rename(f, new_name.replace('-', '@'))
What I would like is if a new file gets added to the directory, then it'll change it too.
But I think because don't have an if/else statement I get an error:
File "/home/Documents/python/renamefiles.py", line 8, in <module>
f_patient, f_conf, f_agmt, f_email = f_name.split('_')
ValueError: need more than 1 value to unpack
So, I wanted to know if I can add something like;
if the new_name is set, then skip and continue the loop.
Thanks for the help! :)
解决方案
您的错误正在发生,因为它遇到的文件不符合您期望的格式......由 . 分隔的四个部分组成_
。
try ... except ...
您可以通过在有问题的行周围使用 a来解决这个问题,continue
如果它不符合该格式,则 -ing 循环。
for f in os.listdir('/home/rachellegarcia/Documents/agreements'):
f_name, f_ext = os.path.splitext(f)
try:
f_patient, f_conf, f_agmt, f_email = f_name.split('_')
except ValueError:
# ... it wasn't the format expected, skip it
continue
# ... it was the format expected
f_agmt_type, f_agmt_staff = f_agmt.split('-')
#sets the new name
new_name = '{}-{}{}'.format(f_agmt_staff, f_email, f_ext)
#renames the file
os.rename(f, new_name.replace('-', '@'))
从长远来看,根据描述您期望的确切格式的正则表达式检查每个文件名可能会更可靠。
推荐阅读
- java - build-impl.xml:919:模块尚未部署
- javascript - 如何使这个不和谐的 webhook 嵌入?
- php - 我不知道如何用主键和外键链接两个表
- html - 位置标签但不包括溢出(位置:绝对)图像
- node.js - WebpackError: RangeError: Gatsby Project 中的时间值无效
- html - Illustrator 创建的 svg 图形未在 html 中正确显示/缩放
- python - 我可以在 lambda 函数中使用 await 吗?
- pdf - 如何将 Google 表格的多个范围导出到单独的 PDF 中?
- nsurl - Xamarin.Mac 使用安全范围的书签
- python - 如何在 Python Spotify API 中更改用户?