[英]Open a file with a pre-defined function (with method)
我有一个预定义的函数,我当前正在运行该函数来检查输入的文件是否正确。 我希望使用 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
不知道具体是什么问题,谢谢! 请注意,代码的第二部分位于其自己的 main 函数中,而不是 open_file 函数的一部分。
当我尝试运行以下代码时,代码给了我一个错误:
f.readline()
date = f.readline()
print_headers()
这是我得到的错误,
with open statement
后面的代码只是一个简单的readline(
"TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper"
您的错误是一个相当简单的修复:只需更换
with open(open_file()) as f:
和
with open_file() as f:
因为您已经打开了文件并在 open_file() 函数中返回了打开的文件。
但是,标准 python 3.x 中不存在 print_headers() 函数,所以我不太确定这是您自己的函数还是其他错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.