如何将带逗号分隔的值的长字符串转换为值的字符串列表

时间:2017-09-18 03:59:21

标签: python split

我正在使用python 3.4.2和visual studio代码我是一个新手 我一直在努力寻找答案,但可能还不足以找到正确的答案。我正在尝试学习python,这是我的学习工具。这是我在80年代早期在TRASH32上基本编写的程序的重做,我无法访问数据文件并且必须手动输入数据。

我想打开一个带有项目(空格,str,int)的长字符串的文件 用逗号分隔。 (例如:“EMD”,“20170820”,1,1,870,“D”,“N”,“BUN”,“)但是大约有450,000个字符。我正在尝试列出一个字符串列表逗号以便我可以调用它们,列表[0:6]返回870,等等 我试过了 -

lines = tuple(open('filename','r'))   # all in only one string.
    print(list)                       # this showed whole file was read.      

我试过 -

with open('filename'):      -this opens file as a list of strings, but only                                                              
    list = line.split(',')    the last third of the file is in the list. 
    print(list)            # this showed whole file was read.                   

我试过 -

with open('filename',('r'))as f:  -this also opens the file as a list of 
   reader = csv.reader(f)         strings, only the last third or so of the 
   list = list(reader)           file is in the list.
print(list)            # this showed whole file was read.                     

我想我的问题是,我可以使用'with open(filename')代码来使整个文件可访问,以便我可以使用它?下面是我的代码示例和结果示例。如果这不可行,我如何将带逗号分隔的值的长字符串转换为字符串列表 价值观。

import sys
import os
import csv

with open('c:/code/EMD0820.DRF'):
    for line in open('c:/code/EMD0820.DRF'):
         list = line.split(',') 
         #print(list)                  # this shows entire file came thru

str_list=str(list)
print (str_list[0:30])                    # this prints out 29 characters 1a
#print(line[0:5])                         # this prints "EMD"    1b
#print(list)                              # this prints lists but only from page 117 of 119 to the end.   1c

print (list[1:15])                        # prints first 14 strings starting where print(line[0:5]) did. 1d

结果

1a  ['"EMD"', '"20170820"', '11', 

1b  "EMD"

1c  ["EMD","20170820",11, 8,,1320,"D",,"C","BUN","Clm2500n2l",6000,............to end of file]

1d [,"20170820",11, 8,,1320,"D",,"C","BUN","Clm2500n2l",6000,2500,2500,66.86]

2 个答案:

答案 0 :(得分:0)

您需要将文件读入内存中的对象。然后你可以拨打split()

尝试:

with open('c:/code/EMD0820.DRF') as f:
    read_file = f.read()
    l = read_file.split(",")

答案 1 :(得分:0)

with open('/path/to/file') as f:
    content = f.read().replace('\n', ',')
    content_list = content.split(',')

print(content_list)