I have a text file called inputs.txt
thats in a folder called task1
the input file contains a series of strings that I need to process in a Python function.
I need to write a function that can open this intputs.txt
file and assign the the string contents to the a variable S
So far I've got:
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
But this throws a syntax error at the forward-slash
The input file currently contains acbcbba, which I want to be passed to the variable S
What am I doing wrong?
EDIT:
I've attached a screen shot of the solution I've tried but I'm still getting the "no file or directory test-input.txt" error
Cheers
There are multiple problems in here:
What is inside the parenthesis in the definition must be a parameter, not a string (so replace that task1/test-input.txt
by something like file
or filename
, because task1/test-input.txt
is what you are trying to open, not a parameter to the function). OR
If you want to open a file named task1/test-input.txt
you need to surround it by quotes (either simple or double, I personnaly prefer double), so "task1/test-input.txt"
the open
function opens a file handle , not the content of the file. You need to call read()
on the handle, then close()
it. So something like:
file = open(filename, "r") S = file.read() file.close() print(S) return S
Also, you should use the with
syntax as pointed out in the comment, which simplifies the above to (since that automatically close
s the handle):
with open(filename, "r") as file: S = file.read() print(S) return S
You need to use a filename variable to pass to the function. To do that you declare a variable with its value encapsulated by quotes like this:
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
Regarding EDIT: The file you are opening needs to be in an accessible path from where you run your script. So if your folder structure looks like this:
task1/
script.py
test-input.txt
You need to call from this path, if you call your script from within "task1/":
path = "test-input.txt
To get your working directory, you can use this snippet to find out:
import os
print(os.getcwd())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.