在上面代码的基础上,考虑txt中包含多个WELLNAME关键字,需要对每一个都导出
时间: 2024-04-10 14:27:46 浏览: 11
要处理多个`WELLNAME`关键字并导出相应的CSV文件,您可以对代码进行一些修改。以下是修改后的代码:
```python
import csv
def extract_well_data(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
well_data = []
wellname = None
start_extract = False
csv_files = [] # 用于存储导出的CSV文件名
for i, line in enumerate(lines):
if "WELLNAME" in line:
if wellname:
csv_file = f"{wellname}.csv"
with open(csv_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows([line.split() for line in well_data])
csv_files.append(csv_file)
wellname = line.split("WELLNAME")[1].strip()
well_data = []
start_extract = True
elif start_extract and "END_TRAJECTORY" in line:
start_extract = False
elif start_extract:
well_data.append(line.strip())
if wellname and well_data: # 处理最后一个WELLNAME关键字之后的数据
csv_file = f"{wellname}.csv"
with open(csv_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows([line.split() for line in well_data])
csv_files.append(csv_file)
return csv_files
# 调用示例
txt_file_path = "your_text_file.txt"
result = extract_well_data(txt_file_path)
if result:
print(f"数据已导出为CSV文件: {result}")
else:
print("未找到适合导出的数据")
```
在修改后的代码中,我们添加了一个`csv_files`列表,用于存储每个导出的CSV文件名。每当遇到一个新的`WELLNAME`关键字时,我们将之前收集到的数据导出为CSV文件,并将文件名添加到`csv_files`列表中。最后,我们还需处理最后一个`WELLNAME`关键字之后的数据。
调用`extract_well_data`函数后,它会返回一个包含所有导出CSV文件名的列表。您可以根据需要进一步处理这些文件名。