-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_data.py
66 lines (50 loc) · 1.89 KB
/
csv_data.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
65
66
# Imports
import csv
# Define a function to pull data from a CSV file.
def pull_csv_data(file_name, desc_loc, item_desc, item_loc):
"""Pulls data from a csv file.
Args:
file_name (str): Name of the file with the extension (must be a csv file).
desc_loc (int): Place on line where the item description is located; starts at 0.
item_desc (str): Description of the item.
item_loc (int): Location of the item itself.
Returns:
str: Value that you seek. Remember to convert to an int, etc. if needed.
"""
# Placeholder value.
value = 'PLACEHOLDER'
# Open the CSV file.
with open(file_name, mode='r') as f:
# Read the CSV file.
csvFile = csv.reader(f)
# Find the content in the CSV file.
for lines in csvFile:
if lines[desc_loc] == item_desc:
value = lines[item_loc]
# Return the value.
return value
# Define a function to rewrite a CSV file.
def rewrite_csv_data(file_name, item_list, separator):
"""Rewrite the CSV file with the new data on one line, separated with semicolons.
Args:
file_name (str): Name of the CSV file.
item_list (list): List of items that should be printed separately.
separator (str): The separator to use in the CSV file.
"""
# Check the file_name variable.
if file_name[-4::] != '.csv':
file_name = file_name + '.csv'
# Read the CSV file.
f = open(file_name, "r+")
lines = f.readlines()
# Ensure the file is not empty before deleting lines.
if len(lines) >= 1:
lines.pop()
# Rewrite the CSV file with all the required data.
f = open(file_name, "w+")
lines = [f"{item}{separator}" for item in item_list]
f.writelines(lines)
# Repeat once again.
f = open(file_name, "w+")
lines = [f"{item}{separator}" for item in item_list]
f.writelines(lines)