I have these list of lines:
lines = (
f"Begin Test 1",
f"Begin Test 2",
f"Begin Test 3",
f"Begin Test 4",
f"Begin Test 5",
f"Begin Test 6",
)
I wanted to just get the first two lines from the first file that contains the lines shown above and concatenate that to another set of lines and then save the new text file.
My code given below, saves the first two lines with double quotes and the rest of the lines without any quotes as viewed with a text editor. How do I get rid of the double quotes in the first two lines and save the data correctly?
Here is my current code:
CODE
import pandas as pd
import os
import contextlib
#
#%%####################### SAVE SCORES TO CSV FILE #####################
lines = (
f"Begin Test 1",
f"Begin Test 2",
f"Begin Test 3",
f"Begin Test 4",
f"Begin Test 5",
f"Begin Test 6",
)
df = pd.DataFrame(lines)
txtfilename = f'Check1.txt'
# Remove csv file if it exists
with contextlib.suppress(FileNotFoundError):
os.remove(txtfilename)
df.to_csv(txtfilename, index=False, header=False)
#%%####################### Save Timing and MODEL INFO for Feature TRAINING #%%#####################
lines22 = (
f"Pre-training accuracy = 50",
f"Total runtime for the Training Process is 20 mins",
f"MODEL DATA:",
f"Figment1"
)
txtfilename2 = f'CheckScrap2.txt'
############ Read first 2 lines of text file #################
with open(txtfilename, 'r') as f:
lines_featExtr = f.readlines()[0:2]
import ast
full_list_lines = tuple(lines_featExtr) lines22
#
df3 = pd.DataFrame(full_list_lines)
#
# Remove txt file if it exists
with contextlib.suppress(FileNotFoundError):
os.remove(txtfilename2)
df3.to_csv(txtfilename2, sep='\n', index=False, header=False)
CodePudding user response:
When you read lines from your txtfiles, there is \n at the end of your strings. ['Begin Test 1\n', 'Begin Test 2\n']
Then using df3.to_csv(txtfilename2, sep='\n', index=False, header=False)
with separator \n induces your problem. Cleaning your lines when reading them does the job:
with open(txtfilename, 'r') as f:
lines_featExtr = f.readlines()[0:2]
lines_featExtr=[lines_featExtr[i].strip('\n') for i in range(len(lines_featExtr))]