我跑的问题是,它并没有打印出任何东西。
是不是有什么毛病我的if语句?因为它打印出来的整个TXT。文件时,我没加if语句。
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
for line in fhand:
line = line.strip()
if line.isupper():
print(line)
该文件包含像HTML,CSS,I / O和SQL,它应该打印出所有的字符串。
要检查平等,使用==
。不过,我敢肯定你是自己找isupper
,不检查它是否相等。 isupper
返回一个布尔值,它可以通过你的if
表达式来进行检查:
for line in fhand:
line = line.strip()
if line.isupper():
print(line)
你if
语句使用它用于分配,不进行比较=
。而是使用==
。除了这些,string.isupper()
这本身就是一个布尔值,因此你将是一个比较字符串和布尔值,它不会产生你想要的结果。
您可以使用filter
函数:
for line in filter(str.isupper, fhand):
print(line)
这可能是更地道打开使用with语句的文件,而不是一个try /除外,因为它处理关闭文件一旦对象到达的范围内结束。 https://docs.python.org/3.6/tutorial/inputoutput.html#reading-and-writing-files
with open(path_to_file, 'r') as fileobj:
for line in fileobj:
if line.strip().isupper():
print(line)
--UPDATE--
从上面往下谁投票这个答案个人的链接:
它与文件对象打交道时使用关键字用好的做法。其优点是,该文件是其整套完成后正常关闭,即使有异常,在某些时候提出的。与使用也比写等价的try-finally块短得多
也
line.strip().isupper()
是完全有效的。
line.strip()返回线对象,该对象的类型是STR(字符串)与去除空格和.isupper()称为该对象上的副本返回一个布尔值。
例
line = ' AES '
print(line.strip().isupper())
将返回true和
line = ' aes '
print(line.strip().isupper())
将返回FALSE
--UPDATE--
为了完整以下@ Tomothy32评论
import os
path_to_file = "/path/to/file"
if os.path.isfile(path_to_file):
with open(path_to_file, 'r') as fileobj:
for line in fileobj:
if line.strip().isupper():
print(line)
else:
print("Please pass valid path to file")
exit()