ChatGPT+Python 入門編 読者特典①
【課題1】
指定したフォルダ以下にある全てのJPGファイルからサムネイル付きのHTMLファイルと、ファイルのフルパスの一覧を作成
import os
import csv
import glob
def find_files(folder_path, file_types):
files_list = []
for file_type in file_types:
files_list.extend(glob.glob(f"{folder_path}/**/*{file_type}", recursive=True))
return files_list
def write_html(files_list, html_filename):
with open(html_filename, 'w', encoding='utf-8') as f:
f.write("<html>\n<body>\n")
for file in files_list:
f.write(f'<p><a href="file:///{file}">{file}</a></p>\n')
f.write("</body>\n</html>")
def write_csv(files_list, csv_filename):
with open(csv_filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
for file in files_list:
writer.writerow([file])
def main():
folder_path = "E:\OneDrive\OneDrive - cvppv\ドキュメント"
file_types = [".pptx", ".xlsx"]
html_filename = os.path.join(folder_path, "ppt-xls-list.html")
csv_filename = os.path.join(folder_path, "pptx-xls-list.csv")
files_list = find_files(folder_path, file_types)
write_html(files_list, html_filename)
write_csv(files_list, csv_filename)
if __name__ == "__main__":
main()