This repository has been archived by the owner on Feb 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConvert.py
49 lines (43 loc) · 1.65 KB
/
Convert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#本程序作用:数据集文件与程序可操作数据集互相转换
import csv
import os
class File: #计算机底层文件操作对象
def __init__(self, dirPath, fileName):
self.DirPath = dirPath
self.FileName = fileName
if (os.path.exists(dirPath) == False):
os.makedirs(dirPath)
def FilePath(self):
return self.DirPath + "\\" + self.FileName
def Write(self, content):
file = open(self.DirPath + "\\" + self.FileName, "w")
file.write(content)
file.close()
def CsvToList(csvFilePath): #将Csv数据集文件转换为列表数据集
with open(csvFilePath,encoding="utf-8") as csvFile:
reader = csv.reader(csvFile)
csvList = []
rowID = 0
for row in reader:
if(rowID != 0):
csvList.append(row)
rowID += 1
return csvList
def ListToCsv(filePath,fileName,fieldnames,data): #将列表数据集转换为Csv数据集文件
csvFile = File(filePath,fileName)
with open(csvFile.FilePath(), 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for row in data:
fieldnamesLen = len(fieldnames)
rowLen = len(row)
if(fieldnamesLen != rowLen): #检查Csv数据与数据名称对称性
return False
else:
CsvRow = {}
ListElement = 0
while(ListElement < fieldnamesLen):
CsvRow[fieldnames[ListElement]] = row[ListElement]
ListElement += 1
writer.writerow(CsvRow)
return True