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 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
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Python | 重命名现有文件(os.rename()方法的示例)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css中的换行符_如何使用CSS防止项目
- 下一篇: Java BigInteger类| is