大写python目录中多个文件的名称

发布于 2025-01-24 18:34:36 字数 641 浏览 3 评论 0原文

我正在研究一个小型项目,该项目要求我使用python在某个目录中使用“ ex:输入:brandy.jpg,output:brandy.jpg”中的所有文件名称。 问题是我以前从未在多个文件上完成过,我所做的是以下内容:

universe = os.listdir('parallel_universe/')
universe = [os.path.splitext(x)[0].upper() for x in universe]

但是我所做的只是在列表中的名称仅但是目录本身中的文件,输出就像以下内容:

['ADAM SANDLER','ANGELINA JULIE','ARIANA GRANDE','BEN AFFLECK','BEN STILLER','BILL GATES', 'BRAD PITT','BRITNEY SPEARS','BRUCE LEE','CAMERON DIAZ','DWAYNE JOHNSON','ELON MUSK','ELTON JOHN','JACK BLACK','JACKIE CHAN','JAMIE FOXX','JASON SEGEL', 'JASON STATHAM'] 

我在这里想念什么?而且,由于我在Python上没有太多经验,因此我希望您的答案包括每个步骤的解释,并提前感谢。

I'm working on a small project that requires that I use Python to uppercase all the names of files in a certain directory "ex: input: Brandy.jpg , output: BRANDY.jpg".
The thing is I've never done on multiple files before, what I've done was the following:

universe = os.listdir('parallel_universe/')
universe = [os.path.splitext(x)[0].upper() for x in universe]

But what I've done capitalized the names in the list only but not the files in the directory itself, the output was like the following:

['ADAM SANDLER','ANGELINA JULIE','ARIANA GRANDE','BEN AFFLECK','BEN STILLER','BILL GATES', 'BRAD PITT','BRITNEY SPEARS','BRUCE LEE','CAMERON DIAZ','DWAYNE JOHNSON','ELON MUSK','ELTON JOHN','JACK BLACK','JACKIE CHAN','JAMIE FOXX','JASON SEGEL', 'JASON STATHAM'] 

What am I missing here? And since I don't have much experience in Python, I'd love if your answers include explanations for each step, and thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好听的两个字的网名 2025-01-31 18:34:36

现在,您将字符串转换为大写,但仅此而已。没有实际的重命名。为了重命名,您需要使用os.Rename

如果要使用OS.RENAME将代码包装,则应解决您的问题,例如:

[os.rename("parallel_universe/" + x, "parallel_universe/" + os.path.splitext(x)[0].upper() + os.path.splitext(x)[1]) for x in universe]

我已删除分配Universe =因为此行不再返回列表,而您将在none对象上获得一堆。

os.rename的文档: https:/ /docs.python.org/3/library/os.html#os.rename

Right now, you are converting the strings to uppercase, but that's it. There is no actual renaming being done. In order to rename, you need to use os.rename

If you were to wrap your code with os.rename, it should solve your problem, like so:

[os.rename("parallel_universe/" + x, "parallel_universe/" + os.path.splitext(x)[0].upper() + os.path.splitext(x)[1]) for x in universe]

I have removed the assignment universe= because this line no longer returns a list and you will instead get a bunch on None objects.

Docs for os.rename: https://docs.python.org/3/library/os.html#os.rename

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文