List program not working - python

I have written a python program to act as a shopping list or some other list editor. It displays the list as it is, then asks if you want to add something, then asks is you want to see the newest version of the list. Here is the code:
#!/usr/bin/python
import sys
def read():
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
print(myList)
myList = []
f.close()
def add_to(str):
newstr = str + "\n"
f = open("test.txt","a") #opens file with name of "test.txt"
f.write(newstr)
f.close()
read()
yes = "yes"
answerone = raw_input("Would you like to add something to the shopping list?")
if answerone == yes:
answertwo = raw_input("Please enter an item to go on the list:")
add_to(bob)
answerthree = raw_input("Would you like to see your modified list?")
if answerthree == yes:
read()
else:
sys.exit()
else:
sys.exit()
When it displays the list it displays it in columns of increasing length.
Instead of this, which is how it appears in the text file:
Shopping List
Soap
Washing Up Liquid
It displays it like this:
['Shopping List\n']
['Shopping List\n', 'Soap\n']
['Shopping List\n', 'Soap\n', 'Washing Up Liquid\n']
I was wondering whether anyone could help me understand why it does this, and how to fix it.
FYI I am using python 2.6.1
EDIT: Thanks to all who commented and answered. I am now trying to edit the code to make it sort the list into alphabetical order, but it is not working. I have written a piece of test code to try and make it work (this would be in the read() function):
#!usr/bin/python
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
f.close()
print myList
subList = []
for i in range(1, len(myList)):
print myList[i]
subList.append(myList[i])
subList.sort()
print subList
This is the text file:
Test List
ball
apple
cat
digger
elephant
and this is the output:
Enigmatist:PYTHON lbligh$ python test.py
['Test List\n', 'ball\n', 'apple\n', 'cat\n', 'digger\n', 'elephant']
ball
apple
cat
digger
elephant
['apple\n', 'ball\n', 'cat\n', 'digger\n', 'elephant']
Once again, any troubleshooting would be helpful.
Thanks
P.S I am now using python 2.7.9

In read, you are printing the whole list after each line read. You just need to print the current line:
def read():
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
print(line)
myList = [] # also you are setting it to empty here
f.close()
Also, you should be using with statement to ensure the closure of the file; and there is no reason to use myList since you are not returning any changes yet; and you'd want to strip() extra whitespace from the beginning and end of the items, so the minimum would be:
def read():
with open('test.txt') as f:
for line in f:
line = line.strip()
print line # this is python 2 print statement
If you need to return a value:
def read():
my_list = []
with open('test.txt') as f:
for line in f:
line = line.strip()
my_list.append(line)
print line
return my_list

Related

How to add numbers to a file

I'm a beginner at Python and I just learned about opening files, reading files, writing files, and appending files.
I would I like to implement this to a little project that I'm making that asks for the user's name and appends it to a txt file named "HallOfFame.txt"
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.read()
print(file_contents)
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + '\n')
name_file.close()
Everytime someone adds their name, I'd like it to become something like this:
Vix
Mike
Valerie
Something similar like that (above) where they have to run the program again to see the Hall of Fame.
Thank you!
I can understand your question. you can try using the JSON module and do something like this.
import json
list = [1, "Vix"]
with open ('HallOfFame.txt', 'w') as filehandle:
json.dump(list, filehandle)
here you can update the list every time you get input. and write it to the text file. but the appearance will look like this.
[1, "Vix"]
[2, "Mike"]
[3, "Valerie"]
count = 0
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.readlines()
if len(file_contents) != 0:
print("\nHall of Fame")
for line in file_contents:
count += 1
print("{}. {}".format(count, line.strip()))
print()
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + "\n")
name_file.close()

writing output on file doesn't work in python

I have the code below to write out a list of N-grams in Python.
from nltk.util import ngrams
def word_grams(words, min=1, max=6):
s = []
for n in range(min, max):
for ngram in ngrams(words, n):
s.append(' '.join(str(i) for i in ngram))
return s
email = open("output.txt", "r")
for line in email.readlines():
with open('file.txt', 'w') as f:
for line in email:
prnt = word_grams(email.split(' '))
f.write("prnt")
email.close()
f.close()
when I print out the word_grams it prints out the files correctly but when it comes to writing the output into files.txt it doesn't work. The "file.txt" is empty.
So I guess the problem must be within these lines of codes:
for line in email.readlines():
with open('file.txt', 'w') as f:
for line in email:
prnt = word_grams(email.split(' '))
f.write("prnt")
email.close()
f.close()
1) the final f.close() does something else than what you want (f inside the loop is another object)
2) You name the file "file.txt" but want the output in "files.txt". Are you sure that you are looking in a correct file?
3) You are overwriting the file for each line in the email. Perhaps the with statement for "file.txt" should be outside the loop.
4) You are writing "prnt" instead of prnt
Something like this?
def word_grams(words, min=1, max=6):
s = []
for n in range(min, max):
for ngram in ngrams(words, n):
s.append(' '.join(str(i) for i in ngram))
return s
with open("output.txt", "r") as email:
with open('file.txt', 'w') as f:
for line in email.readlines():
prnt = word_grams(line.split(' '))
for ngram in prnt:
f.write(ngram)
I don't know what you are trying to accomplish exactly, but it seems that you would like to apply the function word_grams to every word in the file "output.txt" and save the output to a file called "file.txt", probably one item per line.
With these assumptions, I would recommend to rewrite your iteration in this manner:
words = []
# load words from input
with open("output.txt") as f:
for line in f:
words += line.strip().split(" ")
# generate and save output
grams = apply(word_grams, words)
with open("file.txt", "w") as f:
f.write("\n".join(grams))
However, this code assumes that the function word_grams is working properly.
Your code in loop:
for line in email:
did not run!
Because after email.readlines()run,the variable email is empty.
You can do some test like fallows:
email = open("output.txt", "r")
for line in email.readlines():
print '1'
for line in email:
print '2'
if you have 3 lines in your output.txt,after you run this test,you will get:
1
1
1
in the output.
And you can do a test like this:
email = open("output.txt", "r")
email.readlines()
you will see a list with the lines in your output.txt.
but when you run email.readlines()again,you will get an empty list!
so,there should be the problem.your variable email is empty in your second loop.

Read lines from a text file into variables

I have two different functions in my program, one writes an output to a txt file (function A) and the other one reads it and should use it as an input (function B).
Function A works just fine (although i'm always open to suggestions on how i could improve).
It looks like this:
def createFile():
fileName = raw_input("Filename: ")
fileNameExt = fileName + ".txt" #to make sure a .txt extension is used
line1 = "1.1.1"
line2 = int(input("Enter line 2: ")
line3 = int(input("Enter line 3: ")
file = (fileNameExt, "w+")
file.write("%s\n%s\n%s" % (line1, line2, line3))
file.close()
return
This appears to work fine and will create a file like
1.1.1
123
456
Now, function B should use that file as an input. This is how far i've gotten so far:
def loadFile():
loadFileName = raw_input("Filename: ")
loadFile = open(loadFileName, "r")
line1 = loadFile.read(5)
That's where i'm stuck, i know how to use this first 5 characters but i need line 2 and 3 as variables too.
f = open('file.txt')
lines = f.readlines()
f.close()
lines is what you want
Other option:
f = open( "file.txt", "r" )
lines = []
for line in f:
lines.append(line)
f.close()
More read:
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
from string import ascii_uppercase
my_data = dict(zip(ascii_uppercase,open("some_file_to_read.txt"))
print my_data["A"]
this will store them in a dictionary with lettters as keys ... if you really want to cram it into variables(note that in general this is a TERRIBLE idea) you can do
globals().update(my_data)
print A

Python rewriting data text file grades program

Searching for help with a program. The task is to rewrite the program from this question.
The directions are to create a function called def username(first, last):. The function username will have two parameters, first and last. The output will be the same as the original text file grade program.
This is what I have so far:
def username(first, last):
for lines in aList:
n = lines.split()
first = n[0][0].lower()
last = n[1][0:4].lower()
resultName = first + last + "001"
return resultName
def main():
inFile = open("grades.txt", "r")
aList = inFile.readlines()
print(username)
inFile.close
main()
the output I'm receiving:
function username at 0x7f68f83a5158
the output I should be receiving:
>>>username('Jane', 'Smith')
jsmit001
Any insight on what I can do to make this program run correctly would be appreciated.
I played around with this program and found that:
def username(first, last):
inFile = open("grades.txt", "r")
aList = inFile.readlines()
for lines in aList:
n = lines.split()
first = n[0][0].lower()
last = n[1][0:4].lower()
resultName = first + last + "001"
return resultName
infile.close
def main():
print(username(first = "Jane", last = "Smith"))
main()
it works now, but gives me only the first line from my text file. The output is correct, but I need all 5 usernames. I believe it is an indentation problem somewhere but I am unsure where it is. By un-indenting "return resultName" once my output was the last line in my text file.
print(username)
Here you miss the arguments (first,last). At the moment you just ask where the function is saved, so where the pointer is set to
An issue with your program.
You have not called the username function. So when you do
print(username)
the output that you get is the address where the function is stored.
Hope it helps.
def username(first, last):
for lines in aList:
n = lines.split()
first = n[0][0].lower()
last = n[1][0:4].lower()
resultName = first + last + "001"
return resultName
def main():
inFile = open("grades.txt", "r")
aList = inFile.readlines()
#first == aList[0]
#last = aList[1] #Something like this I expect
print(username) ##Pass the values to the function which will return you the value "resultName" which you want to print
inFile.close()
main()

Project to return a line in a text file in python from user input

code = raw_input("Enter Code: ')
for line in open('test.txt', 'r'):
if code in line:
print line
else:
print 'Not in file'
The test.txt file looks like this
A 1234567
AB 2345678
ABC 3456789
ABC1 4567890
When input is A
The print line returns all lines with A instead of just the first line. Note: the test.txt file has approximately 2000 entry's. I just want to return the line with the numbers for what ever the user inputs for now
As #Wooble points out in the comments, the problem is your use of the in operator to test for equivalency rather than membership.
code = raw_input("Enter Code: ")
for line in open('test.txt', 'r'):
if code.upper() == line.split()[0].strip().upper():
print line
else:
print 'Not in file'
# this will print after every line, is that what you want?
That said, probably a better idea (dependent on your use case anyway) is to pull the file into a dictionary and use that instead.
def load(filename):
fileinfo = {}
with open(filename) as in_file:
for line in in_file:
key,value = map(str.strip, line.split())
if key in fileinfo:
# how do you want to handle duplicate keys?
else:
fileinfo[key] = value
return fileinfo
Then after you load it all in:
def pick(from_dict):
choice = raw_input("Pick a key: ")
return from_dict.get(choice, "Not in file")
And run as:
>>> data = load("test.txt")
>>> print(pick(data))
Pick a key: A
1234567

Categories

Resources