I am running through the learn python the hard way tutorials, and I was trying to make my own project that incorporates some of the basic concepts. We haven't covered loops yet, so as a forewarning, if you are going to include a loop in your answer, please do so under the assumption that I've never seen them before :)
this is my code, which works up until I try and write the list to the file. I get the error message that write expected a string. Is there any way to trick write into thinking that the list is a string?
from sys import argv
script, file1 = argv
def rewind(f):
f.seek(0)
txt = open(file1, 'a+')
txt.write(raw_input("What would you like to add to the file?:\n"))
rewind(txt)
text = txt.read()
print text
def breakwords(f):
split_words = f.split(' ')
return split_words
brkwrds = breakwords(text)
print brkwrds
def sort_words(f):
sorted_words = sorted(f)
return sorted_words
sw = sort_words(brkwrds)
rewind(txt)
txt.truncate()
txt.write(sw)
You can join all the strings in the list with str.join
:
my_list = ['a', 'few', 'words']
my_string = ' '.join(my_list)
Here, I'm joining all the string in my_list
using a white space as the separator. The result is a string ( 'a few words'
) that can be written to a file.
You can use pickle to convert the object into a string and then string escape the pickled string so that the result is a single line (when stored in a file).
A python 2X approach is:
from sys import argv
script, file1 = argv
import pickle
def rewind(f):
print(f.seek(0))
f.seek(0)
txt = open(file1, 'a+')
txt.write(raw_input("What would you like to add to the file?:\n"))
rewind(txt)
text = txt.read()
print text
def breakwords(f):
split_words = f.split(' ')
return split_words
brkwrds = breakwords(text)
print brkwrds
def sort_words(f):
sorted_words = sorted(f)
return sorted_words
sw = sort_words(brkwrds)
rewind(txt)
txt.truncate()
txt.write(pickle.dumps(sw).encode("string-escape")+"\n")
txt.close()
To decode the pickled object from the file to get your list back. something like this
my_list_resurrected=pickle.loads(line_in_file.decode("string-escape"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.