如何打开文本文件并将其内容分配给Python函数中的变量?

2024-05-20 16:06:23 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here我有一个名为inputs.txt的文本文件,它位于名为task1的文件夹中。输入文件包含一系列我需要在Python函数中处理的字符串

我需要编写一个函数来打开这个intputs.txt文件,并将字符串内容分配给a变量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

我做错了什么

编辑:

我已经附上了一个我尝试过的解决方案的屏幕截图,但仍然出现“no file or directory test input.txt”错误

干杯


Tags: 文件函数字符串testtxt文件夹内容input
2条回答

您需要使用filename变量来传递给函数。为此,请声明一个变量,其值用引号封装,如下所示:

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())

这里有多个问题:

  1. 定义中括号内的内容必须是参数,而不是字符串(因此将task1/test-input.txt替换为filefilename,因为task1/test-input.txt是您试图打开的内容,而不是函数的参数)。或

  2. 如果你想打开一个名为task1/test-input.txt的文件,你需要用引号把它括起来(简单或双引号,我个人更喜欢双引号),所以"task1/test-input.txt"

  3. open函数打开一个文件句柄,而不是文件内容。您需要在句柄上调用read(),然后close()它。比如:

    file = open(filename, "r")
    S = file.read()
    file.close()
    print(S)
    return S
    
  4. 此外,您应该使用注释中指出的with语法,这将上述内容简化为(因为这会自动close作为句柄):

    with open(filename, "r") as file:
        S = file.read()
    print(S)
    return S
    

相关问题 更多 >