Reputation: 113
Im new in Python and i need some help. i got a .txt file in this form:
Time[tab]Signal
0[tab]1.05
0.5[tab]1.06
1[tab]1.09
1.5[tab]1.12
Now i want to read in the file. I need two lists. List1 should contain the time and list2 should contain the signal.
This is my try:
daten = open("extedit.txt", "r")
lines = daten.readlines();
list1 = []
for i in lines:
list1.append(i.strip().split('\t'));
daten.close()
del list1[1]
print(list1)
Something went wrong i think.. maybe you can help me
i got this in my terminal:
[['{\rtf1\ansi\ansicpg1252\cocoartf1504\cocoasubrtf760'], ['{\colortbl;\red255\green255\blue255;}'], ['{\*\expandedcolortbl;;}'], ['\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0'], ['\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0'], [''], ['\f0\fs24 \cf0 Zeit', 'Signal\'], ['0.01', '1.1\'], ['0.02', '1.105\'], ['0.03', '1.108\'], ['0.04', '1.2\'], ['0.05', '1.205\'], ['0.06', '1.209}']]
Upvotes: 1
Views: 262
Reputation: 315
don't use semicolons in python!
As suspected, you are trying to read a RTF file.
First reformat your file. I propose also an other way:
import csv
list1 = []
with open("extedit.txt") as tsv:
for line in csv.reader(tsv, dialect="excel-tab"):
list1.append(line[0])
del list1[0]
print(list1)
Upvotes: 1
Reputation: 774
I have created a .txt file with same contents that you provided and the program you wrote prints this (multi-dimensional list):
[['Time', 'Signal'], ['0.5', '1.06'], ['1', '1.09'], ['1.5', '1.12']]
By the looks of it your file isn't actually .txt.
To answer your question:
del list1[1]
This will delete the wrong position. To delete Time/Signal line, you should do this instead:
del list1[0]
This is because items in Python lists start at positon 0.
Try this code (list comprehension):
daten = open("extedit.txt", "r")
lines = daten.readlines()
list1 = []
for i in lines:
list1.append(i.strip().split('\t'));
daten.close()
del list1[0]
zeit = [i[0] for i in list1]
signal = [i[1] for i in list1]
print(zeit)
print(signal)
Upvotes: 0
Reputation: 2047
Change the File_Name= according to your needs.
File_Name = 'aa.txt'
time_list = []
signal_list = []
with open(File_Name,'r') as fh:
for line in fh:
line = line.strip()
time,signal = line.split()
time = time.strip()
signal = signal.strip()
time_list.append(time)
signal_list.append(signal)
print(time_list)
print(signal_list)
Upvotes: 1