日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

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

發(fā)布時(shí)間:2025/3/11 python 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python | 重命名现有文件(os.rename()方法的示例) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

重命名現(xiàn)有文件 (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".

要更改現(xiàn)有文件的名稱 –我們使用“ os”模塊的“ rename()”方法 –因此要訪問“ rename()”方法 ,我們必須導(dǎo)入模塊“ os” 。

Module import statement: import os

模塊導(dǎo)入語句: 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是目標(biāo)文件的名稱(新文件的名稱)。

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中更改現(xiàn)有文件名的代碼...在此示例中,我們創(chuàng)建文件file1.txt并在其中寫入“ Hello” ,然后關(guān)閉文件,將file1.txt重命名為myfile.txt 。 要驗(yàn)證操作,請(qǐng)檢查file1.txt是否存在–如果file1.txt不存在,則檢查myfile.txt是否存在–打印其內(nèi)容,并且內(nèi)容為“ Hello” –我們已經(jīng)在file1.txt中編寫了該內(nèi)容。

import osdef main():# creating a file firstfo = open("file1.txt","wt")# writing data in itfo.write("Hello")# closing the filefo.close()# changing the file nameos.rename("file1.txt", "myfile.txt")# checking that file1.txt exists or not# if does not exist - will open myfile and readif 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 filefo = open("myfile.txt", "rt")# reading its contentstr = 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

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的Python | 重命名现有文件(os.rename()方法的示例)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。