简体   繁体   English

如何重命名文件,然后在python的几行中再次找到它?

[英]How do I rename a file and then find it again in few lines in python?

I use os.rename as so: 我这样使用os.rename:

filename, file_extension = os.path.splitext(o)
x = id_generator()
ll = os.rename(o, x + file_extension)

id_generator() just makes a random string, and it does rename the file like I want it to, but since os.rename() doesn't offer anything of value, I can't use it as a variable. id_generator()只是创建一个随机字符串,并且确实按照我想要的方式对文件进行了重命名,但是由于os.rename()没有提供任何有价值的信息,因此我不能将其用作变量。 All I need is to be able to find the renamed file in as few lines as possible and be able to set it as a variable. 我需要的是能够在尽可能少的行中找到重命名的文件,并将其设置为变量。

id_generator() generates a string that has 6 characters and can be numbers and letters. id_generator()生成一个包含6个字符的字符串,可以是数字和字母。

You could simply store the concatenated string in a new variable before you rename the file. 您可以在重命名文件之前将连接字符串简单地存储在新变量中。

filename, file_extension = os.path.splitext(o)
x = id_generator()
# Store new name before os.rename()
new_file = x + file_extension
os.rename(o, new_file)

Now you can use new_file in the rest of the logic. 现在,您可以在其余逻辑中使用new_file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从python脚本仅导入几行? - How do I import only a few lines from a python script? 如何在 Python 中使用随机文件名重命名文件? - How do I rename a file in Python with a random file name? 我正在尝试编写 python 脚本以在文件中查找超过 1000 行的字符串,并在该字符串匹配后删除几行 (10) - I am trying to write python script to find a string in file with more than 1000 lines and delete few lines (10) after that string match 如何使用python删除文件的前几个字符? - How do I remove the first few characters of a file with python? 如果文件已存在于 python 中,我该如何重命名该文件 - How do i rename a file if it already exists in python 如何在几行Python代码中编写许多嵌套的for循环? - How do I write many nested for-loops in a few lines of Python code? 如何拆分这些行以在.txt文件中查找此变量 - How do I split these lines to find this variable in a .txt file Python 2.7:如何一次只从文件中读取几行? - Python 2.7: how to read only a few lines at a time from a file? 在python中跳过几行后如何读取json文件? - How to read the json file after skippinf few lines in python? 我有一个包含几行的.txt 文件。 我必须从中删除所有带有字母“a”的行并将其写入另一个文件。 我该怎么做? - I've got a .txt file with a few lines. I have to remove all the lines with the letter "a" from it and write it to another file. How do I do it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM