Python has several in built functions for strings. We’ll be using the file count_words.py in the WordCount folder. Okay, so we can read a file and print it on the screen. Go to the folder called WordCount, and run the file there: python. On Windows, you’ll need to do: python read_file.py You might have to make the file executable. data = f.read()Īfter opening the file, we read its contents into a variable called data, and close the file. You can also read/write binary files, however we won’t go into that for the moment. Other common modes are w for write, a for append. The r means the file will be opened in a read only mode. Later on, we will cover reading from the command line, but for now, the path is hard coded.
It must exist in the current directory (ie, the directory you are running the code from). We simply open a file called “birds.txt”. It doesn’t do any harm on Windows (as anything that starts with a # is a comment in Python), so we keep it in.
It also tells Linux which interpreter to use (Python in our case). It tells the shell that this is a Python file, and should be run as such. The first line that starts with a #! is used mainly on Linux systems. The file we are working with is read_file.py, which is in the folder Wordcount. This is more interesting than just printing Hello World to the screen. We are going to build a baby version of that. The wc utility is quite advanced, of course, since it has been around for a long time. To get the number of words, lines and characters in a file. Those of you who have used Linux will know this as the wc utility. We will build a simple utility called word counter. Okay folks, we are going to start gentle. This chapter is for those new to Python, but I recommend everyone go through it, just so that we are all on equal footing. Machine Learning with an Amazon like Recommendation Engine Introduction to Pandas with Practical Examples (New)Īudio and Digital Signal Processing (DSP)