我使用R构建了特征向量矩阵,并将其输出到如下所示的文件中:
"","values","vectors.1","vectors.2","vectors.3","vectors.4","vectors.5","vectors.6"
"1",5,0.49,0.40,-0.577,0,0.28,-0.4
"2",4,0,-0.40,0.283,0.5,0.577,-0.4
"3",3,-0.5,0.4,0.28,-0.5,0.28,-0.
"4",3,0.5,-0.4,0.28,-0.5,-0.28,-0.4
"5",1,-0.5,-0.4,-0.57,0,-0.28,-0.4
"6",0,0,0.4,0.28,0.5,-0.57,-0.4
我想删除第一行和第一列以提取矩阵本身并将其存储在另一个文件中(我相信你不能在你打开的同一个文件中进行读写)。因此,我尝试了以下但我不知道如何继续。感谢任何帮助。
with open('./test.csv', 'r') as csvfile, open('./output.csv', 'w') as outputfile:
reader = csv.reader(csvfile, delimiter='\t')
for line in reader:
print line[0][3:]
答案 0 :(得分:1)
您可以在不使用csv
模块的情况下读取和写入CSV文件。您可以遍历除第一行之外的所有行,然后将每行(第一行除外)的所有行写入输出文件,如下所示:
with open('./test.csv', 'r') as input_file, open('./output.csv', 'w') as output_file:
for index, line in enumerate(input_file):
if index != 0:
output_file.write(",".join(line.split(",")[1:]))
请告诉我这是否适合您。
答案 1 :(得分:1)
您可以使用以下内容:
new_file = open("new.csv", "a") # opens/creates new.csv to append the results
with open('old.csv') as f: # opens csv file for reading
f.next() # skips the first line
for line in f: # loop all lines in old.csv
new_file.write(",".join(line.split(",")[1:])) # append to new.csv
new_file.close() # closes new.csv