因此,我有8个不同的.txt文件,我想从其中获取一个数据列,并创建一个包含所有这些数据列的csv文件。我用这个得到了我想要的专栏:
china_data = pd.read_csv('China results.txt', header=None, usecols=[0], sep='\t')但我找不到任何地方解释如何将这些列的数据添加到单个csv文件夹中。
我见过
f.open("filename", "w")但我不确定我能不能用它来做我想做的事。
编辑:我要合并的文件有这样的格式,
0
0 1.0
1 1.0
2 1.0
3 1.0
4 1.0
... ...
14897 1.0
14898 1.0
14899 1.0
14900 1.0
14901 1.0
[14902 rows x 1 columns]发布于 2021-03-08 13:11:36
据我所理解,您需要读取txt文件并将第一列写入csv文件。对于您的usecase,我编写了一些函数来读取csv,提取第一列,将数据的所有第一列组合起来,并在最后将它们写入一个csv文件。为此,需要指定数据文件的文件名。
def read_csv(file_path):
with open(file_path, "r") as f:
lines = f.readlines()
return lines[1:len(lines)-1] #ignoring your first line and last line
def extract_first_column(file_path): #returns first column
lines = read_csv(file_path)
first_col = []
for elem in lines:
elem = elem.strip().split(" ")
if not elem == "":
first_col.append(elem[0])
return first_col
def combined_array(file_path_list): #combines all of columns to one array
all_values = []
for file_path in file_path_list:
col_data = extract_first_column(file_path)
all_values.append(col_data)
return all_values
def write_csv(array, csv_name, delim): #writes the array to a csv file
with open(csv_name,"w") as f:
for elem in array:
if not elem == "":
f.write(elem + delim)
file_name_list = ["data.txt"] #you specify all 7 filenames here
array = combined_array(file_name_list) #array containing all 7 columns
array = [x for sublist in array for x in sublist]
write_csv(array, "test.csv", "\n") #writing to csv file您提供的示例文件对我起了作用。如果我误解了你的要求,我会更新我的答复。
https://stackoverflow.com/questions/66529073
复制相似问题