So im reading every line with this code:
with open ('file.txt') as f: for line in f:
but i want to save every line as a Global accessible string,any way i can do that? Thanks a lot!
CodePudding user response:
Contents of example file foo.txt
:
Hello there
Program :
def can_we_read_it():
print("Here is the contents:")
print(foo)
def get_text(*args, **kwargs) -> str:
with open(*args, **kwargs) as file:
return file.read()
foo = get_text("foo.txt", "r") # foo is available in the global scope,
# it contents 'Hello there' as a string
can_we_read_it()
Content streamed to stdout
:
Here is the contents:
Hello there
Ie, we have the string available in the global scope as we have assigned it to a variable.
CodePudding user response:
The most simple way to store file content in accessible string variable is by using this 2 lines of code:
with open("your_file.txt", "r") as file
content = file.read()
If you want to get a list of lines this is the code that you need:
with open("your_file.txt", "r") as file
content = file.readlines()