Python | 重命名现有文件(os.rename()方法的示例)

重命名现有文件 (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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值