在python中将文件作为列表读取

时间:2017-11-07 17:28:20

标签: python python-3.x list numpy text

将txt文件中的原始字符串导入列表的大多数pythonic方法? " file.txt"的内容看起来像这样(全部在一行中):

["string1","anotha one","more text","foo","2the","bar","fin"]

我可以轻松地将字符串复制/粘贴到我的脚本中,但我确定有更动态的方法。

基本伪代码:

my_list = *contents of file.txt*

4 个答案:

答案 0 :(得分:3)

以json

的形式阅读
import json
with open('file.txt', 'r') as list_file:
    my_list = json.load(list_file)

print (my_list)

输出应为

['string1', 'anotha one', 'more text', 'foo', '2the', 'bar', 'fin']

答案 1 :(得分:2)

来自Python input-output tutorial

  

要读取文件的内容,请调用f.read(size),它会读取一些数据并将其作为字符串返回。 size是可选的数字参数。当size被省略或为负时,将读取并返回文件的全部内容;如果文件的大小是机器内存的两倍,那么这就是你的问题。否则,将读取并返回最多size个字节。如果已到达文件末尾,f.read()将返回一个空字符串("")。

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''

答案 2 :(得分:0)

我有几行:

# Read your single line into the workspace.
with open(fname) as f:
    content = f.readline()
# Process the line to get your list of strings.
processed = [s.strip('[]"') for s in content[0].split(sep=',')]
# processed = ['string1', 'anotha one', 'more text', 'foo', '2the', 'bar', 'fin']

打破第二部分:

  • content[0].split(sep=',')提供['["string1"', '"anotha one"', '"more text"', '"foo"', '"2the"', '"bar"', '"fin"]'],因此它会将您的输入拆分为每个逗号字符的列表,但会从原始输入字符串中留下一些丑陋的额外字符
  • s.strip('[]"')将从字符串"
  • 中删除括号字符的任何实例或双引号字符s
  • [s.strip(...) for s in stuff]将条带应用于新分隔列表中的每个字符串

如果文件中有多行:

# Read your file into the workspace.
with open(fname) as f:
    content = f.readlines()
# Process each line to get your list of strings.
processed = []
for line in content:
    processed.append([s.strip('[]"\n ') for s in line.split(sep=',')])

注意我必须在要剥离的字符上添加换行符和空白字符,以完全清理多行的情况。

答案 3 :(得分:-1)

试试这个,

import re

with open('filename.txt', 'r') as f:

    print [i for i in  re.sub('\s+',' ',f.read()).strip().split(" ")]