How do I get a file to open in a python program and have it do something with the file?
Asked
Active
Viewed 105 times
-3
-
2Possible duplicate of [How to Open a file through python](https://stackoverflow.com/questions/19508703/how-to-open-a-file-through-python) – Nir Alfasi Jan 04 '18 at 07:37
-
Read a file : https://stackoverflow.com/questions/3277503/how-do-i-read-a-file-line-by-line-into-a-list and write in a file : https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file – vvvvv Jan 04 '18 at 07:38
2 Answers
0
Use this with operator will automaticly close file when you code in it executed
with open('your_file_name.extension', 'rw') as myfile:
content = myfile.read()
#do something with content
myfile.write('some string') #add some content

FoxPro
- 2,054
- 4
- 11
- 34
0
the best aproach is to use with
statement.
with open('file.txt', 'w') as file:
file.write('test')
But for more information, follow official documentation: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

simkusr
- 770
- 2
- 11
- 20