Presentation is loading. Please wait.

Presentation is loading. Please wait.

Writing & reading txt files with python 3

Similar presentations


Presentation on theme: "Writing & reading txt files with python 3"— Presentation transcript:

1 Writing & reading txt files with python 3
Txt Files have to be in the same folder as the program

2 Writing to file

3 How to write to a text file
Create a suitable variable to store the name of the text file. Use the code write to add text to the file Close the text file This means ‘write’ This means ‘new line’

4 How to write to a text file
name = open("filename", "w") name = open("filename", "a") Try the ‘a’ What does it do? Change this w to a, what happens

5 Create code to write a list of gas prices in the USA to a file:
Donald says……. Create code to write a list of gas prices in the USA to a file: /21/11 /28/11 /4/11 Call the file ‘GAS PRICES.TXT’

6 Reading from a file

7 f = open("hours.txt“, “r”) print(f.read())
Reading Files Name = open("filename") Name.Read() - file's entire contents as a string Name.Readline() - read next line from file as a string name.Readlines() - file's contents as a list of lines f = open("hours.txt“, “r”) print(f.read())

8 Donald wants you to……. Create code that:
Asks the user to enter in a sentence Saves the sentence to a file Create a new text file with the sentence “make merica great again!” Save it as a file called usa.txt Adapt the program to read this file Use string skills to print the last word

9 print mystring[-1] # print last char
print mystring[5:-1] # result 5678 print mystring[:-1] # everything but the last char print mystring[4:] # from position 4 and onward print mystring[8:100] # result 89

10 Any questions?


Download ppt "Writing & reading txt files with python 3"

Similar presentations


Ads by Google