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

2024-04-19 13:30:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的程序,它可以查看一个文件,找到里面的任何数字,并将它们添加到一个名为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)

我错过了什么?


Tags: 文件in程序renumber内容for文件名
3条回答

使用“with open()as”读取文件,因为它应该自动关闭。否则您需要显式地告诉它关闭文件。

将running_total指定为None会引发我的错误,但将其值设置为0可修复此问题。

另外,不要使用regex和剥离行,只要使用isnumeric()。这也会删除您正在使用的第二个for循环,这应该更有效。

file = input('Enter file name:')
with open(file, 'r') as f:
    file = f.read()
print(file)
running_total = 0
for line in file:
    if line.isnumeric():
        running_total += int(line)
print(running_total)

我用一个txt文件测试了这个问题,这个文件包含自己行上的数字和嵌入在单词中的数字,它正确地找到了所有实例。

编辑:我刚刚意识到海报是想把所有的数字加起来,而不是找到所有的实例。已将running_total += 1更改为running_total += int(line)

我想你应该把跑步总数加到一个可以加进去的数字。

然后,你需要得到文件句柄

正则表达式使得rstrip不必要

running_total = 0
with open(file) as f: 
    for line in f:
        running_total += sum(float(x) for x in re.findall("[0-9]+", line))
print(running_total)

也在这里

https://stackoverflow.com/a/35592562/2308683

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()

……尽管更为惯用的、Pythonic的方法是使用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的对象(这是我在这里更改变量名的原因之一)。

相关问题 更多 >