ตัวอย่าง Python

แสดงชื่อไฟล์ในไดเร็กทอรี

เก็บเฉพาะชื่อไฟล์

from os import walk

mypath = 'C:\\'
liFile = []
for (dirpath, dirnames, filenames) in walk(mypath):
    liFile.extend(filenames)
    break # comment this line

for filename in liFile:
    print(filename)
import glob, os
os.chdir(".")
for file in glob.glob("*.*"):
    print(file)

เก็บ full path

from os import walk

mypath = 'C:\\'
filepaths = []
for (dirpath, dirnames, filenames) in walk(mypath):
    for filename in filenames:
        filepaths.append(dirpath + '\\' + filename)
    break # comment this line
for filepath in filepaths:
    print(filepath)

การเขียนไฟล์ text

text = 'abcde'
filename = 'test.txt'
with open(filename, "w", encoding="utf-8") as f:
    f.write(text)

การอ่านไฟล์ text

filename = 'test.txt'
f = open(filename, "r")
text = f.read()
print(text)
f = open(filename, "r", encoding="utf-8")

การอ่านไฟล์ json

import json

filename = 'test.json'
f = open(filename, "r")
response = json.load(f)
print(response)
print(type(response))
print(response.keys())

date

from datetime import date
date.today()
print(type(date.today()))
print(date.today())
# <class 'datetime.date'>
# 2021-10-14

การรวมไฟล์ .csv ที่มี header แบบง่ายๆ

import os
import glob

merge_file = 'people' # folder name
path = "path_to_csv_folder/" + merge_file

os.chdir(path)
all_files = glob.glob("*.*")
# for file in all_files:
#     print(file)

new_text = ''
for f in range(len(all_files)):
    print(f, all_files[f])

    filename = all_files[f]
    file = open(filename, "r", encoding="utf-8")
    text = file.read()
    lines = text.split('\n')

    if f == 0:
        # print('header of the first file')
        new_text = lines[0] + '\n'

    for j in range(1, len(lines)):
        new_text += lines[j] + '\n'

f = open(merge_file + '.csv', "w", encoding="utf-8")
f.write(new_text.strip('\n'))
f.close()

print('Finish')