重命名现有文件 (Renaming an existing file)
To change the name of an existing file – we use "rename()" method of "os" module – so to access the "rename()" method, we must have to import the module "os".
要更改现有文件的名称 –我们使用“ os”模块的“ rename()”方法 –因此要访问“ rename()”方法 ,我们必须导入模块“ os” 。
Module import statement: import os
模块导入语句: import os
Syntax of rename() method: os.rename(src, dest)
named ()方法的语法: os.rename(src,dest)
Here, src is the name to the source file (old file) and dest is the name of the destination file (new file name).
在这里, src是源文件(旧文件)的名称, dest是目标文件的名称(新文件的名称)。
Example:
例:
Here is the code to change the name of an existing filename in python... In this example, we are creating a file file1.txt and writing "Hello" in it, then, we are closing the file, renaming file1.txt to myfile.txt. To verify the operations, checking file1.txt exists or not – if file1.txt does not exist, checking myfile.txt if it exists – printing its content and the content will be 'Hello" – which we have written in file1.txt.
这是在python中更改现有文件名的代码...在此示例中,我们创建文件file1.txt并在其中写入“ Hello” ,然后关闭文件,将file1.txt重命名为myfile.txt 。 要验证操作,请检查file1.txt是否存在–如果file1.txt不存在,则检查myfile.txt是否存在–打印其内容,并且内容为“ Hello” –我们已经在file1.txt中编写了该内容。
import os
def main():
# creating a file first
fo = open("file1.txt","wt")
# writing data in it
fo.write("Hello")
# closing the file
fo.close()
# changing the file name
os.rename("file1.txt", "myfile.txt")
# checking that file1.txt exists or not
# if does not exist - will open myfile and read
if not(os.path.exists("file1.txt")):
print("file1.txt does not exist.")
# checking myfile, and read its content
if os.path.exists("myfile.txt"):
print("myfile.txt exists, reading its content...")
# opening file
fo = open("myfile.txt", "rt")
# reading its content
str = fo.read()
# printing the content
print("Content of the file: ")
print(str)
else:
print("Operation failed.")
if __name__=="__main__":main()
Output
输出量
file1.txt does not exist.
myfile.txt exists, reading its content...
Content of the file:
Hello
翻译自: https://www.includehelp.com/python/rename-an-existing-file-example-of-os-rename-method.aspx