簡體   English   中英

如何打開文本文件並將其內容分配給 Python function 中的變量?

[英]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”錯誤

干杯

這里有多個問題:

  1. 定義中括號內的內容必須是參數,而不是字符串(因此將task1/test-input.txt替換為filefilename之類的內容,因為task1/test-input.txt是您要打開的內容,不是函數的參數)。 或者

  2. 如果要打開一個名為task1/test-input.txt的文件,則需要用引號將其括起來(簡單或雙引號,我個人更喜歡雙引號),因此"task1/test-input.txt"

  3. open function 打開文件句柄,而不是文件的內容。 您需要在句柄上調用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

您需要使用文件名變量傳遞給 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM