{"id":12088,"date":"2022-03-16T05:14:33","date_gmt":"2022-03-16T09:14:33","guid":{"rendered":"http:\/\/local.brightwhiz\/?post_type=snippets&p=12088"},"modified":"2022-03-16T05:14:36","modified_gmt":"2022-03-16T09:14:36","slug":"how-to-read-a-file-in-python","status":"publish","type":"snippets","link":"http:\/\/local.brightwhiz\/snippets\/how-to-read-a-file-in-python\/","title":{"rendered":"How to Read a File in Python"},"content":{"rendered":"\n
How to read a file Python code example.<\/p>\n\n\n\n
Python make txt file and write to it, open it and catch any errors<\/p>\n\n\n\n
Key:<\/p>\n\n\n\n
‘r<\/strong>‘ open for reading (default)
‘w<\/strong>‘ open for writing, truncating the file first
‘x<\/strong>‘ open for exclusive creation, failing if the file already exists
‘a<\/strong>‘ open for writing, appending to the end of the file if it exists<\/p>\n\n\n\n# read, write, close a file\n# catch error if raise\ntry:\n file = open("TryCatchFile.txt","w") \n file.write("Hello World")\n\n file = open("TryCatchFile.txt", "r")\n print(file.read())\nexcept Exception as e:\n print(e)\nfinally:\n file.close()<\/code><\/pre>\n","protected":false},"comment_status":"open","ping_status":"closed","template":"","meta":[],"categories":[953,25,27,15,16],"tags":[954,350,433,471,475,591,635,638],"yoast_head":"\n