处理数据中不必要的部分,并将处理过的数据写入新的文件中

import os 
import csv
import re
file_path =r'C:\Users\DKTE-assist2009.csv'
file_name =r'C:\Users\remove-DKTE-assist2009.csv'
if os.path.exists(file_path):
    print("文件存在")

with open(file_path, 'r', newline='') as file:
    reader = csv.reader(file)
    
    # 一次性读取整个文件内容并存储在一个列表中
    data = list(reader)
pattern = r'tensor\(([\d.]+),'

for i in range(1,len(data)):
    for j in range(21):
        match = re.search(pattern, data[i][j])
        data[i][j]=float(match.group(1))
with open(file_name, 'a', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

r'C:\Users\DKTE-assist2009.csv'

"r" 表示这是一个原始字符串,其中包含了文件路径。在处理文件路径等可能包含反斜杠符号的字符串时,使用原始字符串是一种良好的做法,可以避免潜在的问题。

如果是逐行写入文件的话:就是writerows和writerow的区别

import os 
import csv
import re
file_path =r'C:\Users\DKTE-assist2009.csv'
file_name =r'C:\Users\remove-DKTE-assist2009.csv'
if os.path.exists(file_path):
    print("文件存在")

with open(file_path, 'r', newline='') as file:
    reader = csv.reader(file)
    
    # 一次性读取整个文件内容并存储在一个列表中
    data = list(reader)
with open(file_name, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(data[0])

pattern = r'tensor\(([\d.]+),'

for i in range(1,len(data)):
    for j in range(21):
        match = re.search(pattern, data[i][j])
        data[i][j]=float(match.group(1))
    with open(file_name, 'a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(data[i])

你可能感兴趣的:(linux,前端,javascript)