-
Notifications
You must be signed in to change notification settings - Fork 0
/
Thesis - .txt to .xlsx (Python)
56 lines (47 loc) · 1.98 KB
/
Thesis - .txt to .xlsx (Python)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import os
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.styles import NamedStyle
folder_path = r"C:\Users\jacob\Documents\Research\IMU Biofeedback Project\Data\WVBF_08\Processed Data"
text_files = [os.path.join(folder_path, filename) for filename in os.listdir(folder_path) if filename.endswith(".txt")]
#text file names to sheet names
sheet_names = [
"WVBF_08 Processed 10_BF_BLS",
"WVBF_08 Processed 10_BLS",
"WVBF_08 Processed 4_BLS",
"WVBF_08 Processed 4_DL_SLS",
"WVBF_08 Processed 4_LSM",
"WVBF_08 Processed 4_ND_SLS",
"WVBF_08 Processed 4_RSM",
"WVBF_08 Processed BFDL_DP",
"WVBF_08 Processed BFDL_MIX",
"WVBF_08 Processed DL_DP",
"WVBF_08 Processed DL_MIX",
"WVBF_08 Processed Jump_1",
"WVBF_08 Processed Jump_2",
"WVBF_08 Processed Jump_3",
"WVBF_08 Processed Jump_4",
]
#New Excel file location
excel_file = os.path.join(folder_path, "WVBF_08 Processed Data.xlsx")
#New excel workbook
wb = Workbook()
# Define a named style with '0' number format to convert to numbers
number_style = NamedStyle(name='number_style', number_format='0')
for file_name, sheet_name in zip(text_files, sheet_names):
# Read the text file into a DataFrame
df = pd.read_csv(file_name, delimiter="\t") # Adjust delimiter as needed
# Create a new sheet with the specified name
ws = wb.create_sheet(title=sheet_name)
# Convert the DataFrame to a list of lists
data = dataframe_to_rows(df, index=False, header=True)
# Add data to sheet and apply the number format
for row_idx, row_data in enumerate(data, start=1):
ws.append(row_data)
for col_idx, cell in enumerate(ws[row_idx], start=1):
cell.style = number_style # Apply the number format to the cell
# remove default sheet
wb.remove(wb.active)
wb.save(excel_file)
print(f"Data from {len(text_files)} text files in '{folder_path}' has been written to separate sheets in {excel_file}.")