(Note: If you're getting a FileNotFoundError already – that's almost to be expected. Here's how to read that file, line-by-line, using a for-loop: myfile = open ( "example.txt" ) for line in myfile : print ( line ) myfile. close ()ĭid that seem too complicated? Here's a less verbose version: myfile = open ( "example.txt" ) print ( myfile. myfile = open ( "example.txt" ) txt = myfile. Here's a short snippet of Python code to open that file and print out its contents to screen – note that this Python code has to be run in the same directory that the example.txt file exists in. If you don't, just create one, and then fill it with these lines and save it: hello world Pretend you have a file named example.txt in the current directory. Let's just go straight to a code example. But before reading that, let's dive into the bare minimum that I want you to know. Here's the official Python documentation on reading and writing from files. The basic pattern of opening and reading files in Python
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |