读入一个.txt文件并将元素放入列表中(Python) [英] Readin a .txt file and put the elements in a list (Python)

查看:1694
本文介绍了读入一个.txt文件并将元素放入列表中(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我需要一些帮助.我收到了以下格式的.txt文件:

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

现在,我想读取文件.我需要两个清单. List1应该包含时间,而list2应该包含信号.

Now i want to read in the file. I need two lists. List1 should contain the time and list2 should contain the signal.

这是我的尝试:

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

我在终端中收到了这个: [['{\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}']]

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}']]

推荐答案

不要在python中使用分号! 疑似,您正在尝试读取RTF文件.
首先重新格式化文件.我还建议另一种方式:

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)

这篇关于读入一个.txt文件并将元素放入列表中(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆