r/pythonhelp • • Jun 12 '20

How can I open a python file with python code?

Title. can I use the os module? can the open() function help? I just can't figure it out.

4 Upvotes

4 comments sorted by

1

u/Thrasherop Jun 12 '20

https://www.w3schools.com/python/ref_func_open.asp

There's a link to some good explanation

2

u/e4c6 Jun 12 '20

oh this is perfect thanks!

1

u/Thrasherop Jun 12 '20

Use this:

f = open("filename.txt","mode") Contents = f.read() f.write("some text") f.close()

modes are this: "a" is append. What you write will just ad to the end. "r" read mode. You can only read the file. "w+" mode. Which creates the file. If the file is already created, it truncates the old file and replaces it.