Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 程序内未打开文件归档_Python - Fatal编程技术网

Python 程序内未打开文件归档

Python 程序内未打开文件归档,python,Python,所以我已经输入了我的完整代码,它将运行,但它不会从程序中的文件中读取 def main(): #Variables num_upper = 0 num_lower = 0 num_space = 0 num_digits = 0 data = '' #Opening text.txt for reading infile = open('text.txt', 'r') #Read data from file d

所以我已经输入了我的完整代码,它将运行,但它不会从程序中的文件中读取

def main():
    #Variables
    num_upper = 0
    num_lower = 0
    num_space = 0
    num_digits = 0
    data = ''

    #Opening text.txt for reading
    infile = open('text.txt', 'r')

    #Read data from file
    data = infile.read()
    
    #Ste through each character in the file
    #Determine the varying variables and keep a total of each
    for ch in infile:
        if ch.isupper():
            num_upper = num_upper + 1
        if ch.islower():
            num_lower = num_lower + 1
        if ch.isdigit():
            num_digits = num_digits + 1
        if ch.isspace():
            num_space = num_space + 1

    #Close file
    infile.close()

    #Display totals
    print('The number of uppercase letters in the file:', num_upper)
    print('The number of lowercase letters in the file:', num_lower)
    print('The number of digits in the file:', num_digits)
    print('The number of whitespace in the file:', num_space)

#calling main
main()

我很确定我的问题来自“内嵌”和“数据”,但我不确定如何改进它。任何帮助都将不胜感激。

如果您试图迭代文件流,即
infle
,请尝试迭代
数据

for ch in data:
    ...
    ...
您可以使用
with
语句with
open
。它在
之后提供带有
块的关闭流

还有,为什么要检查字符4次?尝试使用
elif
来提高性能

with open("test.txt", "r") as f:
    data = f.read()
    for ch in data:
        if ch.isspace():
            num_space += 1
        elif ch.isdigit():
            num_digits += 1
        elif ch.isupper():
            num_upper += 1
        elif ch.islower():
            num_lower += 1

您正在尝试迭代文件流,该文件流是
infle
,请尝试迭代
数据

for ch in data:
    ...
    ...
您可以使用
with
语句with
open
。它在
之后提供带有
块的关闭流

还有,为什么要检查字符4次?尝试使用
elif
来提高性能

with open("test.txt", "r") as f:
    data = f.read()
    for ch in data:
        if ch.isspace():
            num_space += 1
        elif ch.isdigit():
            num_digits += 1
        elif ch.isupper():
            num_upper += 1
        elif ch.islower():
            num_lower += 1

乍一看,ch in INFLE:
应该是ch in data:
。就是这样。谢谢你,伙计!乍一看,ch in INFLE:
应该是ch in data:
。就是这样。谢谢你,伙计!