[英]Opening files from filepaths on windows
我尝试定义一个 function 它将采用文件路径并将其转换为字符串。 这是我想出的辩护:
def get_book(file_path):
'''Takes a file path and returns the entire book as a string.'''
with open(file_path, 'r', 'utf-8') as infile:
content = infile.read()
return content
AnnaKarenina = get_book('../Python/Data/books/AnnaKarenina.txt')
我现在得到 TypeError: an integer is required (got type str)
我还尝试使用 os.path、不同种类的斜杠和其他技巧来打开带有 windows 的文件,但都返回找不到错误文件。
有谁知道我做错了什么?
open
function 的编码参数是一个命名参数,所以必须这样指定:
def get_book(file_path):
'''Takes a file path and returns the entire book as a string.'''
with open(file_path, 'r', encoding='utf-8') as infile:
content = infile.read()
return content
AnnaKarenina = get_book('../Python/Data/books/AnnaKarenina.txt')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.