将.txt用于列表中

时间:2017-01-30 16:34:07

标签: python

嗨,大家只是需要帮助将.txt读入列表我认为到目前为止我已经得到了

r = open('RegsInList.txt','r')

rr =(r.readlines())
#print(rr)

这可以导入文本文件并读取它我需要它来读入列表。所以我可以把它放在列表obj之下,然后把它拆分

listobj = ['AV46 WAD','WD40 ASD','BG65 KYS','WA48 DFT','GH09 DEG']
var1, var2, var3,var4 ,var5 = listobj
print(var1)
print(var2)
print(var3)
print(var4)
print(var5)

我的.txt看起来像,

'AV46 WAD','WD40 ASD','BG65 KYS','WA48 DFT','GH09 DEG'

感谢帮助,如果你能给予

编辑:

time1list = open('time1.txt','r')
time1 =(time1list.readlines())
#print(regs)

listobj = time1[0].replace("'", '').split(',')
time11, time12, time13,time14 ,time15 = listobj
print(time11)
print(time12)
print(time13)
print(time14)
print(time15)

给我错误

追踪(最近一次通话):   文件“/Users/GameDevelopment/Desktop/Desktop/Python/AvgSpeed/Times/Time1Split.py”,第2行,in     time1 =(time1list.readlines())   文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings/ascii.py”,第26行,解码     return codecs.ascii_decode(input,self.errors)[0] UnicodeDecodeError:'ascii'编解码器无法解码位置0的字节0xe2:序数不在范围内(128)

2 个答案:

答案 0 :(得分:0)

您可以将此.txt读入列表并按以下方式打印:

with open("test.txt", "r") as infile:
    content = [i.strip("'") for i in infile.read().split(",")]
for i in content:
    print(i)

答案 1 :(得分:0)

以下是实现目标的步骤:

  1. 阅读文件
  2. 按行','
  3. 拆分每行中的项目
  4. 将每个项目添加到列表
  5. 示例代码:

        with open("input.txt","r")  as fp:
            lines = fp.readline()
    
        for line in lines:
             listobj = line.split(",")
    
        for item in listobj:
             print(item)