【问题标题】:Open multiple files using path = open() feature使用 path = open() 功能打开多个文件
【发布时间】:2016-08-13 18:59:25
【问题描述】:

在我学习数组时,我一直在一些开始的 python 脚本中使用 path = open(Testfilename)。现在我正在处理字典,我想看看是否可以使用此功能打开多个文件。

fav_cars = {}

for c in cars: #I have a few separate CSV files with different cars
    path = open()

我本质上想围绕用户放入的不同汽车进行循环。如上所述,我知道如何打开单个文件,但我正在尝试学习打开多个文件。我试着做:

path = open('F-150.csv', 'Silverado.csv', 'Mustang.csv', 'Tesla.csv', 'r'),

但这不起作用,因为我收到了错误代码TypeError: an integer is required

更新:

汽车文件由一列组成,标题称为“颜色”。六种颜色有6行:红、蓝、黄、黑、白、绿

cars = ['F-150','Silverado','Mustang','Tesla','Juke','Corolla']

fav_cars = {}   
for c in cars: 
    path = open () # wanting to open multiple files here
    car_colors = {} #colors for each car in cars
    for temp_dict in path:
         if not temp_dict.startswith("#"): #to get rid of the header "colors in the file
             if values in user_input: #value is the car color
                   car_colors.update({values})
                   fav_cars.update({c:car_colors})

当我使用 raw_input 调用它时,我只使用用户输入的汽车 user_inputs。希望这会有所帮助。

【问题讨论】:

  • 打开文件后您想对它们做什么?
  • 您能否提供一些汽车 csv 文件、预期用户输入和预期输出的示例?

标签: python python-2.7 loops dictionary path


【解决方案1】:

你应该这样做:

fav_cars = {}

for c in cars:
    with open(c, 'r') as f:
       fav_vars[c] = f.readlines()

内置open 函数只需要一个文件作为参数,第二个是您打开的文件模式。

【讨论】:

  • 我这样做但得到错误 AttributeError: 'file' object has no attribute 'startswith'。我使用 : if not temp_dict.startswith("#") 所以我可以删除标题。
  • 我认为您在阅读文件之前尝试对文件内容进行操作。我修改了答案以将文件内容添加到文件对象的列表中。
  • 嗯。 fav_cars 仍然只给我 {} 的输出。
  • @Caroline.py,您从不在自己的代码中使用 fav_cars,那么我们应该如何知道如何处理它?
  • @PadraicCunningham 我很抱歉。我是字典新手。我假设这会打开文件并将其设置为名为 fav_cars 的字典,但忘记使用 fav_cars.update({values}),其中 values 是每个汽车文件中列格式的颜色列表。
猜你喜欢
  • 1970-01-01
  • 2011-06-04
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
相关资源
最近更新 更多