如何在Python 3中使用input()读取文件

巴鲁克·伊利亚斯

我有一个简单的程序,它可以查看文件,查找其中的任何数字,并将它们加到一个名为running_total的变量中。我的问题似乎是我的文件名是正在读取的东西,而不是其内容。

import re

file = input('Enter file name:')
open(file)
print(file)
running_total = None

for line in file:
    line = line.rstrip()
    numbers = re.findall("[0-9]+", line)
    print(numbers)
    for number in numbers:
        running_total += float(number)

print(running_total)

我想念什么?

ez

file是一个字符串,表示从input函数中出来的文件名,它仍然是一个字符串。因此,当您遍历该文件时,将一一获得文件名的字母。当您调用时open(file),返回一个可以迭代以提供文件内容的对象,但是您当前没有为该对象命名或重新使用它。您的意思确实是这样的:

file_name = input('Enter file name:')
file_handle = open(file_name)   # this doesn't change file_name, but it does output something new (let's call that file_handle)
for line in file_handle:
    ....
file_handle.close()

...虽然更惯用的Python方式是使用一条with语句:

file_name = input('Enter file name:')
with open(file_name) as file_handle:
    for line in file_handle:
        ....
# and then you don't have to worry about closing the file at the end (or about whether it has been left open if an exception occurs)

请注意,变量file_handle是一个其类被调用的对象file(这是我在此处更改变量名称的原因之一)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Python3中使用opencv从文件缓冲区读取文件

如何在python中使用pandas从csv文件中读取?

如何在Python 3中使用面向对象的编程读取文本文件

如何在Python 3中使用readlines读取由空格分隔的整数输入文件?

如何在bash脚本中使用文件描述符3中的“读取”进行读取?

如何在bash脚本中使用文件描述符3中的“读取”进行读取?

如何在Python 3中使用raw_input

如何在CodeIgniter 3中使用PHPSpreadsheet从Excel(.xlsx和.xls)文件读取数据?

如何在python中使用pyarrow从S3读取分区实木复合地板文件

如何在Python中使用熊猫跳过读取空文件

如何在grep命令中使用从文件中读取的行

如何在Python中从文本文件读取input()

如何在python3中使用python2 input()函数?

如何在sqlite3中使用python中的模式文件创建db文件

如何在Python中从S3读取Avro文件?

如何在 Python 3 中从 AWS 读取 Excel 文件?

如何在Python 3中的函数中使用raw_input作为参数

如何在Python中逐行读取文件?

如何在Python中逐行读取文件?

如何在python中读取.log文件?

如何在Python Flask中读取文件

如何在Python中从文件读取整数

如何在python中读取属性文件

如何在Python中读取Excel文件?

在Python 3中使用io.BufferedReader快速读取gzip(文本文件)

如何在Spyder 3中使用Python 3?

如何在Selenium Webdriver Python 3中使用Chrome配置文件

如何在Python3中使用变量创建json文件路径?

如何在Python 3中使用urllib中的basejoin