0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで任意フォルダ内の全ての.pyファイルを.txtとしてコピーする

Posted at

任意のフォルダ内の.pyファイルを全て同じ名前の.txtとしてコピーしたい.

スクリーンショット 2024-11-07 8.48.53.jpg

copy_py_txt.py
# -*- coding: utf-8 -*-
import os
import shutil

def copy_py_to_txt(folder_path):
    # フォルダ内の全ファイルをリストアップ
    for filename in os.listdir(folder_path):
        # .pyファイルを探す
        if filename.endswith('.py'):
            # 元のファイルのフルパス
            source_path = os.path.join(folder_path, filename)
            
            # 新しいファイル名(拡張子を.txtに変更)
            new_filename = os.path.splitext(filename)[0] + '.txt'
            
            # 新しいファイルのフルパス
            destination_path = os.path.join(folder_path, new_filename)
            
            # ファイルをコピー
            shutil.copy2(source_path, destination_path)
            print(f"Copied: {filename} -> {new_filename}")

# 使用例
folder_path = r'/Desktop/名称未設定フォルダ'  # ここにフォルダのパスを入力してください
copy_py_to_txt(folder_path)

同じファイル名で,拡張子がtxtのファイルがコピーされる.

スクリーンショット 2024-11-07 8.50.16.jpg

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?