如何从python中的文件制作元组列表 [英] how to make a list of tuples from a file in python

查看:65
本文介绍了如何从python中的文件制作元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有一个像这样的文件.

Ok I have a file like that looks like this.

panite,1,1800
ruby,2,100
diamond,0.75,900
emerald,3,250
amethyst,2,50
opal,1,300
sapphire,0.5,750
benitoite,1,2000
malachite,1,60

我们的老师给了我们使用try/except的代码来帮助我们打开文件.我需要打开文件并阅读每一行,并将每一行设置为一个元组,然后将其放入列表中.该列表应该是最后一个数字除以中间的数字,然后是该值,后跟宝石的名称(中间的数字是宝石的克拉).我遇到的问题是我什至无法从文件中列出列表.这就是我试图打开它没有太大的成功.

Our teacher gave us code that uses a try/except to help us open the file. I need to open the file and read each line and make each line a tuple and then put it in a list. The list is supposed to be the last numbe divided by the middle number, and then that value followed by the name of the gem(the middle number is the carat of the gem). The problem i'm having is I cant even get it to make a list from the file. This is what i've tried to open it without much success.

def main():
    fileFound = False
    while not fileFound:
        fileName = input('File name containing jewel data: ')
        try:
            dataFile = open(fileName, "r")
            fileFound = True
            knapsack()
        except:
            print ('Could not find that file -- try again')

def knapsack():
    list = dataFile.readline()

当我在def knapsack()下将其更改为简单的printstatement时,我实际上取得了一些成功,它将打印诸如2 + 2之类的简单内容,但是当我尝试创建列表时,它给了我例外的错误反而.这是我的第一门编程课,因此对此有任何见解将不胜感激.

I've actually had a little success when I changed it to a simple printstatement under def knapsack() where it will print something simple like 2+2, but when I try to make a list, it gives me the except error instead. This is my first programming class so any insight into this would be appreciated.

推荐答案

def make_jewel(line):
    name, carats, price = line.split(",")
    return (float(price)/float(carats), name)

def main():
    while True:
        file_name = input('File name containing jewel data: ')
        try:
            with open(file_name) as inf:
                data = [make_jewel(line) for line in inf]
            break
        except FileNotFoundError:
            print('Could not find that file -- try again')

main()

和一些评论:

    没有指定异常类型的
  • except:,也就是所谓的裸异常",因为它捕获了一切而被皱了皱眉.您应该指定希望看到的异常类型,并且仅处理这些异常.如果您捕获了所有内容,但完全出乎预料的失败(例如ComputerOnFireError!),您将一无所获.

  • except: without a specified exception-type, also known as a "bare exception", is frowned on because it catches everything. You should specify the type of exceptions you expect to see, and only handle those; if you catch everything and something totally unexpected fails (ie ComputerOnFireError !) you will never find out about it.

使用with打开文件,因为这样可以确保始终正确关闭文件.

opening a file using with is preferred because it ensures the file will always get closed properly.

以文本模式打开文件时,可以逐行遍历该文件;这是处理文件的最常用方法.

when you open a file in text mode, you can iterate over it line-by-line; this is the most common way to process a file.

.split()字符串时,会返回一个字符串列表.在对片段进行数学运算之前,必须使用int()float()将它们从字符串转换为数值.

when you .split() a string, you get a list of strings back. Before doing math on the pieces you have to convert them from a string to a numeric value using int() or float().

希望有帮助.

这篇关于如何从python中的文件制作元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆