Python maths quiz alphabetical sorting - python-3.x

I'm struggling to get my code to work on python it is meant to print the data in alphabetical order but doesn't can anyone help?
if choice.lower() == 'az':
dictionary={}
fi = open("class1.txt",'r')
data = fi.readlines()
for line in sorted(data):
print(data.rstrip());

You don't need to use readlines here, sorted is able to iterate over the file just fine. You should be printing line.strip() instead of data.strip()
with open("class1.txt",'r') as fi:
for line in sorted(fi):
print(line.rstrip())
I've also shown you how to use a context manager here (the with line). This causes the file to be closed automatically at the end of the block

You're applying rstrip wrong:
print(line.rstrip());
should do the trick.

Related

system is not writing into original dictionary file

def update(login_info):
stids = 001
file = open('regis.txt', 'r+')
for line in file:
if stids in line:
x = eval(line)
print(x)
c = input('what course you would like to update >> ')
get = x.get(c)
print('This is your current mark for the course', get)
mark = input('What is the new mark? >>')
g = mark.upper()
x.update({c: g})
file.write(str(x))
Before writing into the file
After writing into the file
This is what happens in the idle
As you can see, the system is not writing the data into the original dictionary. How can we improve on that? Pls, explain in detail. Thx all
Python doesn't just make relations like that. In Python's perspective, you are reading a regular text file, executing a command from the line read. That command creates an object which has no relationship to the line it was created from. But writing to the file should still work in my opinion. But you moved a line further (because you read the line where the data was and now you are at the end of it).
When you read a file, the position of where we are on the file changes. Iterating over the file like that (i.e for line in file:) invokes implicitly next() on the file. For efficiency reasons, positioning is disabled (file.tell() will not tell the current position). When you wrote to the file, for some reason you appended the text to the end, and if you test it it will no longer continue the loop even though it is still on the second line.
Reading and writing at the same time looks like an undefined behaviour.
Beginner Python: Reading and writing to the same file

CSV reader with .txt file [duplicate]

I use python and I don't know how to do.
I want to read lots of lines in files. But I have to read from second lines. All files have different lines, So I don't know how to do.
Code example is that it read from first line to 16th lines.
But I have to read files from second lines to the end of lines.
Thank you!:)
with open('filename') as fin:
for line in islice(fin, 1, 16):
print line
You should be able to call next and discard the first line:
with open('filename') as fin:
next(fin) # cast into oblivion
for line in fin:
... # do something
This is simple and easy because of the nature of fin, being a generator.
with open("filename", "rb") as fin:
print(fin.readlines()[1:])
Looking at the documentation for islice
itertools.islice(iterable, stop)
itertools.islice(iterable, start, stop[, step])
Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line).
I think you can just tell it to start at the second line and iterate until the end. e.g.
with open('filename') as fin:
for line in islice(fin, 2, None): # <--- change 1 to 2 and 16 to None
print line

Index Error - For Line in File: line.split into [1] and [2]

might be a silly question but maybe still someone can help me out. So inside my code i'm trying to use a text file to grap some log in data and repeat it. The code which is not working is the following.
Accs.txt file looks like:
User1:Passwort1
User2:Passwort2
User3:Passwort3
code.py looks like:
file = open('Accs.txt', 'r')
for acc in file:
Mail=acc.split(':')[0]
Passwort=acc.split(':')[1]
print (Mail)
print (Passwort)
after the text file graps the second acc on the list i get an index error. I guess there is some logical thing behind how it works which i dont get. Anybody could help me out?
I ran the same code and it worked fine.
If there are any extra blank lines in your text file, that index out of range exception can be thrown.
here is a workaround to handle blank lines (source: python: how to check if a line is an empty line)
for acc in file:
if acc.strip():
lineSplit = acc.split(':')
Mail=lineSplit[0]
Passwort=lineSplit[1]
print (Mail)
print (Passwort)
Also , it is more efficient to use the split() method one time and store into a variable to access later by index later (also in code above)
You should go
for line in file.read():
line = line.split(":")
mail=line[0]
pass=line[1]
Read the file must go file.read()
Sorry for the layout I'm using my phone :)

read login data from text file into dictionary error

Using the answer on Stack Overflow shown on this link: https://stackoverflow.com/a/4804039, I have attempted to read in the file contents into a dictionary. There is an error that I cannot seem to fix.
Code
def login():
print("====Login====")
userinfo={}
with open("userinfo.txt","r") as f:
for line in f:
(key,val)=line.split()
userinfo[key]=val
print(userinfo)
File Contents
{'user1': 'pass'}
{'user2': 'foo'}
{'user3': 'boo'}
Error:
(key,val)=line.split()
ValueError: not enough values to unpack (expected 2, got 0)
I have a question to which I would very much appreciate a two fold answer
What is the best and most efficient way to read in file contents, as shown, into a dictionary, noting that it has already been stored in dictionary format.
Is there a way to WRITE to a dictionary to make this "reading" easier? My code for writing to the userinfo.txt file in the first place is shown below
Write code
with open("userinfo.txt","a",newline="")as fo:
writer=csv.writer(fo)
writer.writerow([{username:password}])
Could any answers please attempt the following
Provide a solution to the error using the original code
Suggest the best method to do the same thing (simplest for teaching purposes) Note, that I do not wish to use pickle, json or anything other than very basic file handling (so only reading from a text file or csv reader/writer tools). For instance, would it be best to read the file contents into a list and then convert the list into a dictionary? Or is there any other way?
Is there a method of writing a dictionary to a text file using csv reader or other basic txt file handling, so that the reading of the file contents into a dictionary could be done more effectively on the other end.
Update:
Blank line removed, and the code works but produces the erroneous output:
{"{"Vjr':": "'open123'}", "{'mvj':": "'mvv123'}"}
I think I need to understand the split and strip commands and how to use them in this context to produce the desired result (reading the contents into a dictionary userinfo)
Well let's start with the basics first. The error message:
ValueError: not enough values to unpack (expected 2, got 0)
means a line was empty, so do you have a blank line in the file?
Yes, there are other options on saving your dictionary out and bringing it back, but first you should understand this, and may work just fine for you. :-) The split() is acting on the string you read from the file, and by default will split on the space, so that is what you are seeing. You could format your text file like 'username:pass' instead and then use split(':").
File Contents
user1:pass
user2:foo
user3:boo
Code
def login():
print("====Login====")
userinfo={}
with open("userinfo.txt","r") as f:
for line in f:
(key,val)=line.split(':')
userinfo[key]=val.strip()
print(userinfo)
if __name__ == '__main__':
login()
This simple format may be best if you want to be able to edit the text file by hand, and I like to keep it simple as possible. ;-)

Checking/Writing lines to a .txt file using Python

I'm new both to this site and python, so go easy on me. Using Python 3.3
I'm making a hangman-esque game, and all is working bar one aspect. I want to check whether a string is in a .txt file, and if not, write it on a new line at the end of the .txt file. Currently, I can write to the text file on a new line, but if the string already exists, it still writes to the text file, my code is below:
Note that my text file has each string on a seperate line
write = 1
if over == 1:
print("I Win")
wordlibrary = file('allwords.txt')
for line in wordlibrary:
if trial in line:
write = 0
if write == 1:
with open("allwords.txt", "a") as text_file:
text_file.write("\n")
text_file.write(trial)
Is this really the indentation from your program?
As written above, in the first iteration of the loop on wordlibrary,
the trial is compared to the line, and since (from your symptoms) it is not contained in the first line, the program moves on to the next part of the loop: since write==1, it will append trial to the text_file.
cheers,
Amnon
You dont need to know the number of lines present in the file beforehand. Just use a file iterator. You can find the documentation here : http://docs.python.org/2/library/stdtypes.html#bltin-file-objects
Pay special attention to the readlines method.

Resources