PYTHON DICTIONARY
CommentsData typesVariablesIf ElseIf Elif ElseFunctionsFor loopWhile loopData structuresString slicing/indexingUser defined functionLocal/Global variableValidation and TryMethodsFile I/OPseudocodeModules |
What does file I/O even mean?Basic file operations
Working with text filesin Windows, "Notepad" is the name of the program that lets you make "text files". Search for it on your Windows device, it should be there.
Notice below how the text file and python file are saved in the same folder. They must be saved in the same folder otherwise your code will not "see" your text file. Python challenge - writing to a text fileEnter the following code in a Python code editor. Before running the code, what do you think it will do? Press "F5" then "Enter" to run
In this example, the "w" means "write" which means to add what ever the user writes into the text file called read_it. "Write" and "close" are methods for the variable called notepad which hold the value of the created and opened "read_it.txt" file. "w" is not the only mode of opening a file. Below is a table that shows all the other modes available.
CHALLENGE: Extend the code above to ask for Last name and age and then save the data in the text file as First name and Surname on one line and age on the next line below. Python challenge - Reading from text fileDownload the following text file from here. Enter the following code below in a Python code editor. Save both the code and the downloaded text file in to the same folder (rename the text file as "lines.txt"). Before running the code, what do you think it will do? Press "F5" then "Enter" to run
Selected text file access modes
Selected file object methods
Python challenge - writing to a text fileEnter the following code in a Python code editor. Before running the code, what do you think it will do? Press "F5" then "Enter" to run
Here a user defined function contains code that opens the text file called "lines.txt". There is a for loop that reads every line of the poem in the text file and brings it into an empty array called "SomeData_list". More about {.replace} and {.split} can be found in methods. More about the return statement can be found here.
|