从列表转换为元组时从文本文件中删除双引号

Remove double quotes from text file when converting from list to tuple

我有这些行列表:

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",
    )

我只想从包含上面显示的行的第一个文件中获取前两行并将其连接到另一组行,然后保存新的文本文件。

我在下面给出的代码,用双引号保存前两行,用文本编辑器查看其余行时没有任何引号。如何去除前两行中的双引号并正确保存数据?

这是我当前的代码:

代码

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)

当您从 txt 文件中读取行时,字符串末尾有 \n。 ['Begin Test 1\n', 'Begin Test 2\n']

然后将 df3.to_csv(txtfilename2, sep='\n', index=False, header=False) 与分隔符 \n 一起使用会引发您的问题。阅读时清理你的台词就可以了:

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))]