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
语句withopen
。它在之后提供带有块的关闭流
还有,为什么要检查字符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
语句withopen
。它在之后提供带有块的关闭流
还有,为什么要检查字符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:
的。就是这样。谢谢你,伙计!