我有一个预定义的功能,我目前正在运行,以检查文件输入是否正确。我希望在函数中用with“运算符打开此文件。这就是我目前拥有的:
def open_file():
'''Checks if the file is correct.'''
grab_file = True #Creates initial variable that checks if file is correct
while grab_file == True: #Loop initiates the check if true
txt = input("Enter a file name: ") #Asks for file input
try:
f = open(txt) #Tries to open the file
return f #File returned as output
grab_file = False #Stops the loop
except: #File is invalid, prompts for retry
print("Error. Please try again.")
def main():
'''Main function that runs through file and does delta calculations.'''
with open(open_file()) as f:
f.readline()
print_headers()
pass
不知道到底是什么问题,谢谢!注意代码的第二部分在它自己的主函数中,而不是open文件函数的一部分。
当我尝试运行以下程序时,代码显示一个错误:
f.readline()
date = f.readline()
print_headers()
This is the error I am getting, the code after the
with open statement
are just a simplereadline(
"TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper"
您的错误很容易修复: 只需更换
与
因为您已经打开了文件,并在open_file()函数中返回了打开的文件。你知道吗
但是print_headers()函数在标准python3.x中不存在,所以我不确定这是您自己的函数还是另一个错误。你知道吗
相关问题 更多 >
编程相关推荐