forked from EnguerranVidal/HYG-STAR-MAP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
64 lines (52 loc) · 2.09 KB
/
database.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# PROJECT DECEMBRE 2019
# PROJECT STAR MAP / DATABASE
# By Enguerran VIDAL
# This file contains the database handling functions.
###############################################################
# IMPORTS #
###############################################################
import csv
###############################################################
# FUNCTIONS #
###############################################################
def csv2txt(csv_file, txt_file):
''' Transforms a csv file into a txt file '''
with open(txt_file, "w") as my_output_file:
print(" Opened new txt file")
with open(csv_file, "r") as my_input_file:
print(" Opened old csv file")
[my_output_file.write(",".join(row) + '\n') for row in csv.reader(my_input_file)]
my_output_file.close()
def format_txt(txt_file, char1, char2):
''' Changes "char1" into "char2" throughout an entire .txt file.'''
with open(txt_file, "r") as file:
lines = file.readlines()
file.close()
with open(txt_file, "w") as file:
n = len(lines)
for i in range(n):
lines[i] = lines[i].replace(char1, char2)
file.write(lines[i])
file.close()
def import_database(txt_file):
''' Returns the data from a .txt file transformed from a csv file'''
with open(txt_file, "r") as file:
lines = file.readlines()
n = len(lines)
for i in range(n):
lines[i] = lines[i].split(',')
m = len(lines[i])
for j in range(m):
if lines[i][j] == '' or lines[i][j] == '\n':
lines[i][j] = 'N'
labels = lines[0]
lines.pop(0)
return labels, lines
def dat2csv(dat_file, csv_file):
with open(dat_file) as infile, open(csv_file, "w") as outfile:
csv_writer = csv.writer(outfile)
prev = ''
csv_writer.writerow(['ID', 'PARENT_ID'])
for line in infile.read().splitlines():
csv_writer.writerow([line, prev])
prev = line