chevron_left chevron_right
Login Register invert_colors photo_library


Stay updated and chat with others! - Join the Discord!
Thread Rating:
  • 0 Vote(s) - 0 Average


[2.7] Reading and writing to a textfile filter_list
Author
Message
[2.7] Reading and writing to a textfile #1
As per usual, this tutorial is for Python 2.7.

Firstly, how do we read the contents of a textfile into a string variable in python?

Code:
file = open('C:/Users/Harvey/Desktop/test.txt', 'r')
my_string = file.read()
file.close()

print my_string

Firstly, we create a variable called 'file'. That can be whatever you like. We use the open() function with the parameters of the location of my textfile and 'r' which means read. In the second line, we create a string variable and write everything from within the textfile into it. Don't forget to close your textfile after finishing with it!

We now have the contents of a textfile in a string (my_string). So, how do we write to a textfile?

Code:
text_to_add = 'We want to add this to our textfile'
file = open('C:/Users/Harvey/Desktop/test.txt', 'w')
file.write(text_to_add)
file.close()

We create a string to hold what we want to store in our textfile (text_to_add). We then use the open() function again but our second parameter is 'w' this time (write). We then write the string of text to the textfile and close it.

This replaces anything that was previously in the textfile with whatever was written. If there is no such file as 'test.txt', it will create a new one.

What if you don't want to completely overwrite everything in the textfile, but you just want to append some new text? Instead of using the second parameter of 'w' in the open() function, use 'a' for append.

Any question? :'D Class dismissed.

Reply

RE: [2.7] Reading and writing to a textfile #2
Very Interesting Harvey, Thanks for the share.

Reply

RE: [2.7] Reading and writing to a textfile #3
(04-12-2013, 11:38 AM)Redbull Wrote: Very Interesting Harvey, Thanks for the share.

No worries mate!

Reply






Users browsing this thread: 1 Guest(s)