請你幫我將兩段代碼整合 file_contents = [] file_count = 0 for file_name in os.listdir(src_folder): if file_name.endswith('.txt'): file_count += 1 file_path = os.path.join(src_folder, file_name) if date.fromtimestamp(os.path.getmtime(file_path)) == today: with open(file_path, 'r', encoding='gbk') as t: # 只保留最后一行 last_line = None for line in t: last_line = line.strip() if last_line: # 将文件名和最后一行内容用逗号分隔,并写入列表 file_contents.append(file_name + ',' + last_line)# 获取今天的日期 today_str = datetime.datetime.now().strftime('%Y/%m/%d')# 只保留包含今天日期的行 lines = [line for line in lines if today_str in line]
时间: 2024-02-14 07:04:54 浏览: 65
以下是整合後的代碼:
```python
file_contents = []
file_count = 0
today_str = datetime.datetime.now().strftime('%Y/%m/%d')
for file_name in os.listdir(src_folder):
if file_name.endswith('.txt'):
file_count += 1
file_path = os.path.join(src_folder, file_name)
if date.fromtimestamp(os.path.getmtime(file_path)) == today:
with open(file_path, 'r', encoding='gbk') as t:
last_line = None
for line in t:
last_line = line.strip()
if last_line:
file_contents.append(file_name + ',' + last_line)
with open(file_path, 'r', encoding='gbk') as t:
lines = t.readlines()
lines = [line.strip() for line in lines]
lines = [line for line in lines if today_str in line]
file_contents.append(file_name + ',' + ','.join(lines))
```
這段代碼首先定義了一個空列表 file_contents 和一個整數 file_count。然後,它從指定的 src_folder 中遍歷所有以 .txt 結尾的文件。如果該文件的修改日期是今天,則它會打開文件,讀取並保留最後一行,然後將文件名和最後一行內容用逗號分隔並添加到 file_contents 中。接下來,它會再次打開文件,讀取所有行並只保留包含今天日期的行,然後將文件名和這些行內容用逗號分隔並添加到 file_contents 中。最後,該代碼返回 file_contents 列表。
阅读全文