To create, read, and write to a file in Python
To create, read, and write to a file in Python, you can use the open()
function. Here are some examples:
-
Creating a file:
file = open("filename.txt", "w") file.write("Hello world!") file.close()
This will create a new file called "filename.txt" and write the string "Hello world!" to it.
-
Reading a file:
file = open("filename.txt", "r") contents = file.read() file.close() print(contents)
This opens the file "filename.txt" that we created in the previous example, reads its contents into the variable
contents
, and prints them to the console. -
Appending to a file:
file = open("filename.txt", "a") file.write("\nThis is a new line.") file.close()
This opens the file "filename.txt" in append mode and adds the string "\nThis is a new line." to the end of the file.
There are other modes you can use with open()
, such as "r+" (read and write) and "a+" (read and append). For more information, check out the official Python documentation on file input/output.
To read and write Markdown files in Python
To read and write Markdown files in Python, you can use the markdown
library, which provides a way to convert Markdown text to HTML and vice versa. Here’s an example of how to use it:
-
Installing the
markdown
library:pip install markdown
-
Reading a Markdown file:
import markdown
with open("filename.md", "r") as f:
md_text = f.read()
html = markdown.markdown(md_text)
print(html)
This reads a Markdown file called "filename.md", converts the text to HTML using the markdown()
function, and prints the resulting HTML to the console.
3. Writing to a Markdown file:
import markdown
html = "<h1>Hello world!</h1>"
md_text = markdown.markdown(html)
with open("filename.md", "w") as f:
f.write(md_text)
This writes the string "Hello world!
" to a Markdown file called "filename.md" as converted Markdown text, using the write()
function.
Note that you can also use the markdown2
library, which is a newer version of the markdown
library with some additional features. You can install it using pip install markdown2
.