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?

More than 1 year has passed since last update.

【Python】複数のテキストファイルから更新日時と特定の一行をCSVへ出力するスクリプト

Last updated at Posted at 2023-03-20
import os
import csv
from pathlib import Path
import time

output_csv = "output.csv"
specific_line_number = 1
max_directories = 1000

base_path = "//"
dir_pattern = "nnn/test"
file_name = "hoge.txt"

with open(output_csv, mode='w', newline='', encoding='utf-8') as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(["Directory", "Text Line", "File Update Time"])

    for i in range(max_directories):
        dir_name = str(i).zfill(3)
        dir_path = base_path + dir_name + dir_pattern
        file_path = os.path.join(dir_path, file_name)

        if os.path.isfile(file_path):
            with open(file_path, encoding='utf-8') as txt_file:
                try:
                    specific_line = txt_file.readlines()[specific_line_number - 1].strip()
                except IndexError:
                    specific_line = ""

            file_update_time = os.path.getmtime(file_path)
            file_update_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(file_update_time))

            csv_writer.writerow([dir_path, specific_line, file_update_time_str])

print("CSVファイルに出力が完了しました。")
import os
import csv
from pathlib import Path
import time

output_csv = "output.csv"
search_string = "特定の文字列"
max_directories = 1000

base_path = "//"
dir_pattern = "hogennn/test"
file_name = "hoge.txt"

def find_line_with_string(file, search_string):
    with open(file, encoding='utf-8') as txt_file:
        for line_number, line in enumerate(txt_file, start=1):
            if search_string in line:
                return line.strip(), line_number
    return "", -1

with open(output_csv, mode='w', newline='', encoding='utf-8') as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(["Directory", "Text Line", "Line Number", "File Update Time"])
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?