How to open file as formatted string?
You can do something like file.read().format(myvar=’myself’) , or if you prefer to have all the replacements in a dict like replacements = <'myvar': 'myself'>and then file.read().format(**replacements) . If you want to use variable names, then file.read().format(**locals()) or file.read().format(**globals()) .'myvar':>
@jdehesa could you please explain further how the .format(**locals()) or **globals() would work? I would still need to use a dictionary such as replacements that you showed right?
@Sosi No, locals() and globals() return a dictionary themselves, so unpacking them with ** will directly make them work as keyword-based replacements.
@Sosi I’m gonna star this and try to come back with a good answer this evening if someone hasn’t made one by then
2 Answers 2
This seems to work if the variable is local to the call, if it’s a global variable, use **globals() . You can also put the value in a dictionary that has the variable name as the key.
myvar = 'myself' newline = '\n' # Avoids SyntaxError: f-string expr cannot include a backslash with open('unformatted.txt', 'r') as file: myfile = f"".format(**locals()) print(myfile)
Before seeing this answer, I spent 30 mins trying to understand why a working example was fine (such as the one you give), but when I had it in a function it wasn’t working. Now I see why 🙂
Assume there is «This is .» in file.txt.
with open('path/to/file.txt', 'r') as file: myfile = file.read().replace('\n', '') myvar='myself' print(myfile.format(myvar=myvar))
Any strings in plain text format, can be imported as a variable from a text file. Then the strings variable can be manipulated as normal.
In you case, the key is «». So you can easily use «.format(var=varx) as long as you defined variable «varx».
And if you want to import html template with css style and replace some contents, you can just use «>» to escape «».
Read File as a String in Python
In this Python tutorial, you will learn how to read a file as a string, and the examples cover different scenarios like incorporating file checks before reading.
Python – Read File as String
You can read whole content of a file to a string in Python.
Generally, to read file content as a string, you follow these steps.
- Open file in read mode. Call inbuilt open() function with file path as argument. open() function returns a file object.
- Call read() method on the file object. read() method returns whole content of the file as a string.
- Close the file by calling close() method on the file object.
The default mode is text mode for open() function. So, even if you do not provide any mode for open() function, the read operation should work fine.
Examples
In the following examples, we write Python programs to read the text file given by a path, and store it as a string value.
1. Read file as a string
In this example, we assume that we a file with two lines of content present in the location D:/data.txt . We shall apply the sequence of steps mentioned above, and read the whole content of file to a string.
Python Program
#open text file in read mode text_file = open("D:/data.txt", "r") #read whole file to a string data = text_file.read() #close file text_file.close() print(data)
Hello World! Welcome to www.tutorialkart.com.
2. Negative scenario – File path incorrect while reading the file
In this example, we assume that we are trying to read content of a file that is not present. In other words, file path is incorrect.
Python Program
#open text file in read mode text_file = open("D:/data123.txt", "r") #read whole file to a string data = text_file.read() #close file text_file.close() print(data)
Traceback (most recent call last): File "d:/workspace/fipics/rough.py", line 2, in text_file = open("D:/data123.txt", "r") FileNotFoundError: [Errno 2] No such file or directory: 'D:/data123.txt'
There is our FileNotFoundError. And the message says that no such file or directory with the file path passed to open() function.
3. Check if file is present before reading file to a string
In this example, before reading a file, we shall check if the file present. Only after we make a confirmation that the file present, we shall read its content to a string.
To check if a file is present, we use os.path.isfile() function.
Python Program
import os file_path = "D:/data123.txt" #check if file is present if os.path.isfile(file_path): #open text file in read mode text_file = open(file_path, "r") #read whole file to a string data = text_file.read() #close file text_file.close() print(data)
Now, try with the file paths that is present and not present. If the file is present, you read the text from file, else you don’t. But, no runtime error from Python Interpreter.
Conclusion
In this Python Tutorial, we learned how to read file content to a string.