迭代文件读取

时间:2017-06-17 20:23:58

标签: python python-3.x

在Windows 10上使用Python 3.5.2 :: Anaconda 4.0.0(64位)。

我有一个名为upgrade.csv的文件,其中包含:

['$APPL','$FB','$MSLI','$AMZN','$NVDA','$WMT','$NFLX']

我想循环遍历这些股票代码。

使用以下代码从文件中提取返回:

[
'
$
A
P
P
L
'
,
'
$
F
B
'
,

等等通过数据。

第一个代码:

file = open('upgrades.csv', 'r')
upgrades = (file.read())
file.close()
upgrades = list(upgrades)
for i in range(len(upgrades)):
    print(upgrades[i])

从显式字符串中拉出会返回我想要的内容:

$APPL
$FB
$MSLI
$AMZN
$NVDA
$WMT
$NFLX

第二段代码:

upgrades = ['$APPL','$FB','$MSLI','$AMZN','$NVDA','$WMT','$NFLX']
upgrades = list(upgrades)
for i in range(len(upgrades)):
    print(upgrades[i])

请帮我从文件中提取数据并获得此结果:

$APPL
$FB
$MSLI
$AMZN
$NVDA
$WMT
$NFLX

我尝试过将数据转换为:

upgrades = list(upgrades)
upgrades = str(upgrades)
upgrades = tuple(upgrades)

我也尝试将文件从csv更改为txt。

2 个答案:

答案 0 :(得分:1)

将其视为单行csv并按以下步骤操作。

with open('upgrades.csv', 'r') as upgrade:
    for line in upgrade.readlines():
        lines = line.split(",")
        for m in lines:print m

答案 1 :(得分:0)

In[5]: import json
  ...: 
  ...: with open('upgrades.csv', 'r') as f:
  ...:     data = json.loads(f.read().replace("'", '"'))
  ...: 
  ...: print(data)
  ...: for item in data:
  ...:     print(item)
  ...: 
['$APPL', '$FB', '$MSLI', '$AMZN', '$NVDA', '$WMT', '$NFLX']
$APPL
$FB
$MSLI
$AMZN
$NVDA
$WMT
$NFLX

In[6]: from ast import literal_eval
  ...: 
  ...: with open('upgrades.csv', 'r') as f:
  ...:     data = literal_eval(f.read())
  ...: 
  ...: print(data)
  ...: for item in data:
  ...:     print(item)
  ...: 
['$APPL', '$FB', '$MSLI', '$AMZN', '$NVDA', '$WMT', '$NFLX']
$APPL
$FB
$MSLI
$AMZN
$NVDA
$WMT
$NFLX