import os import pandas as pd def txt_to_excel(txt_path, excel_path): # 读取txt文件 with open(txt_path, 'r') as f: lines = f.readlines() # 解析txt文件中的数据 data = [] for line in lines: items = line.strip().split() year, month, day, precip = items[0], items[1], items[2], items[3] # 将降水值转为浮点型并将-999和负值替换为0 precip = float(precip) if precip < 0 or precip == -999: precip = 0 data.append([year, month, day, precip]) # 将数据转为DataFrame格式,并添加表头 df = pd.DataFrame(data, columns=['年', '月', '日', '降水']) # 保存为Excel文件 df.to_excel(excel_path, index=False, engine='openpyxl') def traverse_files(folder_path): # 遍历指定文件夹中的txt文件,并转换为Excel文件 for root, dirs, files in os.walk(folder_path): for file in files: if file.endswith('.txt'): # 构造Excel文件名 excel_name = os.path.splitext(file)[0].split('-')[-1] + '.xls' excel_path = os.path.join(root, excel_name) txt_path = os.path.join(root, file) txt_to_excel(txt_path, excel_path) if __name__ == '__main__': folder_path = 'E:/project/work5-8' traverse_files(folder_path)
时间: 2023-06-18 09:02:13 浏览: 59
这段代码的功能是将指定文件夹中的所有以 .txt 结尾的文件读取并解析数据,然后将数据保存为 Excel 文件。具体实现流程如下:
1. traverse_files 函数通过 os.walk 遍历指定文件夹中的所有文件。
2. 对于每个文件,如果文件名以 .txt 结尾,则调用 txt_to_excel 函数将文件内容解析并保存为 Excel。
3. txt_to_excel 函数首先使用 open 函数读取 txt 文件内容。
4. 然后对每一行数据进行解析,提取年、月、日和降水值,并将降水值转为浮点型。
5. 如果降水值为负数或 -999,则将其替换为 0。
6. 最后将解析后的数据转为 DataFrame 格式,并添加表头。
7. 最后将 DataFrame 保存为 Excel 文件。
注意:在运行代码前需要确保 openpyxl 库已经安装。
相关问题
import os import pandas as pd import time while True: start = time.perf_counter() def get_txt_files(folder_path): files = [] try: for root, dirs, filenames in os.walk(folder_path): for filename in filenames: if filename.endswith(".txt"): files.append(os.path.abspath(os.path.join(root, filename))) except Exception as e: print("Error: {}".format(e)) return files def combine_txt_files(txt_files): content = "" try: for txt_file in txt_files: with open(txt_file, "r") as f: content += f.read() except Exception as e: print("Error: {}".format(e)) return content def write_combined_content_to_file(content, file_path): try: with open(file_path, "w") as f: f.write(content) except Exception as e: print("Error: {}".format(e)) def txt_to_excel(txt_file, excel_file): try: df = pd.read_csv(txt_file, delimiter="\t", header=None) df.to_excel(excel_file, index=False, header=None) except Exception as e: print("Error: {}".format(e)) if __name__=="__main__": folder_path="Z:\看板v2" txt_files=get_txt_files(folder_path) combined_content=combine_txt_files(txt_files) combined_file_path="D:\\測試log\\TXT合1并.txt" write_combined_content_to_file(combined_content,combined_file_path) excel_file_path="D:\\測試log\\123.xlsx" txt_to_excel(combined_file_path,excel_file_path) end = time.perf_counter() print('運行時間為:{}秒'.format(end-start)) time.sleep(30)
这是一段 Python 代码,主要功能是将指定文件夹中的所有 .txt 文件合并为一个文件,并将合并后的内容转换为 Excel 文件。
首先使用 `os.walk` 函数获取指定文件夹中所有的 .txt 文件路径,然后使用 `open` 函数读取每个文件的内容,并将所有内容合并为一个字符串。接着使用 `open` 函数将合并后的字符串写入到指定路径的文件中。最后使用 Pandas 库中的 `read_csv` 函数读取合并后的文本文件,并使用 `to_excel` 函数将其转换为 Excel 文件。
代码中使用了一个死循环,每隔 30 秒就会执行一次上述操作。遇到任何异常都会输出错误信息。最后会输出每次操作的运行时间。
def deal_txt(path): """ 读取path的txt文件,处理后返回DataFrame :param path: :return: """ with open(path,'rb') as f: result=chardet.detect(f.read())#自动检测文本编码格式 try: df = pd.read_csv(path, sep='|', header=None, encoding=result['encoding'] )怎么将上述代码加入这段代码中
您可以将上述代码放在deal_txt函数的开始部分,代码如下:
```python
import chardet
import pandas as pd
def deal_txt(path):
with open(path,'rb') as f:
result=chardet.detect(f.read())
try:
df = pd.read_csv(path, sep='|', header=None, encoding=result['encoding'])
# 在这里进行DataFrame处理
return df
except Exception as e:
print(e)
```
这样,您就可以在读取txt文件后,直接对DataFrame进行处理了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)