d读取log文件,遇到"My name is kitty"时,从读到的下一行开始逐行写入csv。改进代码。 ef read_log_file(file_path): """ """ with open(file_path, 'r') as f: start_writing = False lines = [] for line in f: if start_writing: lines.append(line) if "My name is kitty" in line: start_writing = True with open('output.csv', 'w') as out_file: out_file.write("\n".join(lines))
时间: 2024-02-14 14:11:03 浏览: 134
CSVConversionDatatable_C#CSV文件读取写入_
可以考虑使用Python内置的csv模块来写入csv文件,同时可以使用try-except语句来捕获文件读写异常。改进后的代码如下:
```python
import csv
def read_log_file(file_path):
with open(file_path, 'r') as f, open('output.csv', 'w', newline='') as out_file:
writer = csv.writer(out_file)
start_writing = False
for line in f:
if start_writing:
try:
writer.writerow([line.strip()])
except csv.Error as e:
print(f"Error writing row: {e}")
if "My name is kitty" in line:
start_writing = True
```
在这个改进后的函数中,我们使用了csv.writer对象来写入csv文件。同时,我们使用了try-except语句来捕获写入csv文件时可能会出现的异常。由于我们使用了newline=''参数来打开输出文件,因此写入csv文件时不会出现额外的空行。
阅读全文