Many times, we might want to store information in files. Python allows us to easily, write, read, or change any information in a file. To access a file, you write open("fileName.txt", "mode"). In the first argument, you write the file name. Make sure that the file is in the same folder as your Python program. Otherwise, you would have to write the whole file path in the first argument. In the second, we have to tell Python what we want to do with the file. Do we want to read it, write it, both? Here are some examples:
To read a file, you have to first open the file and save that in a variable, then use the .readlines() method to put the lines inside the file in a list. You can then print the list to read it.
Notice how there are some newline characters in the list. To remove it, we can use the .strip() method we discussed earlier to get rid of those characters. Here is an example:
Now it looks clean.
To write in a file, you have two options, to make changes or to add something in a file (append), or to rewrite the entire file (write). Both writing and appending in a file uses the same methods but they are just two different types. If you want to write in a file that doesn't exist, it will create a new one for you. Here is an example of writing and appending in a file:
Make a program that asks for the user input and whatever the user says, it will go in a file. But if the user types read, it will print the file lines for the user.
Copyright © 2024 PieceOfAPie - All Rights Reserved.
Powered by GoDaddy
We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.