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"])