![](/img/trans.png)
[英]How can I assign the contents of a .txt file to a string variable in Python?
[英]How can I open a text file and assign it's contents to a variable in a Python function?
我有一个名为
inputs.txt
的文本文件,它位于一个名为task1
的文件夹中,输入文件包含一系列我需要在 Python function 中处理的字符串。
我需要编写一个 function 可以打开这个intputs.txt
文件并将字符串内容分配给变量S
到目前为止,我有:
def open_func(task1/test-input.txt): # syntax error thrown here with forward-slash
S = open(task1/test-input.txt, "r")
print(S)
return S
但这会在正斜杠处引发语法错误
输入文件当前包含 acbcbba,我想将其传递给变量 S
我究竟做错了什么?
编辑:
我附上了我尝试过的解决方案的屏幕截图,但我仍然收到“无文件或目录 test-input.txt”错误
干杯
这里有多个问题:
定义中括号内的内容必须是参数,而不是字符串(因此将task1/test-input.txt
替换为file
或filename
之类的内容,因为task1/test-input.txt
是您要打开的内容,不是函数的参数)。 或者
如果要打开一个名为task1/test-input.txt
的文件,则需要用引号将其括起来(简单或双引号,我个人更喜欢双引号),因此"task1/test-input.txt"
open
function 打开文件句柄,而不是文件的内容。 您需要在句柄上调用read()
,然后close()
它。 所以像:
file = open(filename, "r") S = file.read() file.close() print(S) return S
此外,您应该使用注释中指出的with
语法,它将上述简化为(因为自动close
句柄):
with open(filename, "r") as file: S = file.read() print(S) return S
您需要使用文件名变量传递给 function。 为此,您声明一个变量,其值用引号封装,如下所示:
def open_func(filename):
f = open(filename, "r")
content = f.read()
f.close()
print(content)
return content
path = "task1/test-input.txt"
content = open_func(path)
# do something with the file content now
关于编辑:您打开的文件需要位于运行脚本的可访问路径中。 因此,如果您的文件夹结构如下所示:
task1/
script.py
test-input.txt
如果您从“task1/”中调用脚本,则需要从此路径调用:
path = "test-input.txt
要获取您的工作目录,您可以使用此代码段找出:
import os
print(os.getcwd())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.