The below function parses multiple csv files in a directory and takes out values using str.startwith().
It works find using ‘firstline.startswith(‘TrakPro’)‘ and ‘txt.startswith('Serial')
‘. However, when I add a third str.startwith() i.e. txt2.startswith(‘Test’), nothing prints out, no error, appears to ignore it. What do I need to change? Basically I want to add multiple str.startwith() in the for loop pulling out various key words after the ‘:”.
JavaScript
x
29
29
1
def get_csv_file_list(root):
2
for r, d, f in os.walk(root):
3
for file in f:
4
5
if file.endswith('.csv'):
6
path = os.path.join(r, file)
7
dir_name = path.split(os.path.sep)[-2]
8
file_name = os.path.basename(file)
9
10
try:
11
with open(path) as k:
12
firstline = k.readline()
13
14
if firstline.startswith('TrakPro'):
15
file_list.append(path)
16
file_list.append(dir_name)
17
file_list.append(file_name)
18
19
txt = 'Serial Number:'
20
if txt.startswith('Serial'):
21
for row in list(k)[3:4]:
22
file_list.append(row[15:26])
23
24
txt2 = 'Test Name:'
25
if txt2.startswith('Test'):
26
for rows in list(k)[4:5]:
27
print(rows)
28
file_list.append(row[11:])
29
The csv looks like this:
JavaScript
1
12
12
1
TrakPro Version 5.2.0.0 ASCII Data File
2
Instrument Name:,SidePak
3
Model Number:,TK0W02
4
Serial Number:,120k2136005
5
Test Name:,13270
6
Start Date:,04/17/2021
7
Start Time:,01:53:29
8
Duration (dd:hh:mm:ss):,00:07:13:00
9
Log Interval (mm:ss):,01:00
10
Number of points:,433
11
Description:,
12
So far I have tried the above code, I expected to print out values in the ‘Test Name’ line of the csv sample. The function does not print out anything, no error.
Tks
Advertisement
Answer
To print only the value of the line that starts with Test Name:
you can use following code:
JavaScript
1
6
1
with open("your_file.csv", "r") as f_in:
2
for line in map(str.strip, f_in):
3
if line.startswith("Test Name:"):
4
_, value = line.split(",", maxsplit=1)
5
print(value)
6
Prints:
JavaScript
1
2
1
13270
2