Reading list from text file and converting it to string - python

Hello, I recently started to learn Python, so that's my best explain to you, cause my English skills are not Perfectly.
I made a script which is reading a list from text file, and then my problem is converting it to string, so I could display it in the print function. After doing that, when user is typing his "Nickname", lets say. The script is already readen the list from text file. Also the i don't know if used the split(',') Function, that should split the words with those , from the words in the text file used for list. Here are some pictures of my code.
https://gyazo.com/db797ca0998286248bf846ac70c94067 (Main code)
https://gyazo.com/918aaba9b749116d842fccb78f6204a8 (Text file - list of usernames which are "BANNED")
The text code file name is Listas_BAN.txt.
I've tried to do all this thing myself, i did some research before posting this, but many methods are outdated.
# Name
name = input("~ Please enter Your name below\n")
print("Welcome " + str(name))
def clear(): return os.system('cls')
clear() # Clearina viska.
# define empty list
Ban_Listo_Read = open('Listas_BAN.txt', mode='r')
Ban_Listo_Read = Ban_Listo_Read.readlines()
Ban = Ban_Listo_Read.list(ban)
# Print the function (LIST) in string .
print("Your'e Banned. You'r nickname is - ", + Ban_Listo_Read).Select (' %s ', %s str(name)) # Select the User nickname from
# The input which he typed. (Check for BAN, In the List.)
# Text file is the List Location . - Listas_BAN.txt
enter image description here
enter image description here
I'm getting Wrong Syntax Error

ll = open('untitled.txt', mode='r').readlines()
print("".join(ll).replace('\n', '.'))
name = input("~ Please enter Your name below\n")
if name in ll:
print('your name {n} is in the list'.format(n=name))
EDIT:
plus, you shall consider using string formatting:
var1 = ...
var2 = ...
print("{x}...{y}".format(x=var1, y=var2)
or python 3.7
print(f"{var1}...{var2}")
EDIT:
f.readlines()
https://docs.python.org/3.7/tutorial/inputoutput.html
If you want to read all the lines of a file in a list you can also use
list(f) or f.readlines().

Related

delete only 1 instance of a string from a file

I have a file that looks like this:
1234:AnneShirly:anneshirley#seneca.ca:4:5\[SRT111,OPS105,OPS110,SPR100,ENG100\]
3217:Illyas:illay#seneca.ca:2:4\[SRT211,OPS225,SPR200,ENG200\]
1127:john Marcus:johnmarcus#seneca.ca:1:4\[SRT111,OPS105,SPR100,ENG100\]
0001:Amin Malik:amin_malik#seneca.ca:1:3\[OPS105,SPR100,ENG100\]
I want to be able to ask the user for an input(the student number at the beginning of each line) and then ask which course they want to delete(the course codes are the list). So the program would delete the course from the list in the student number without deleting other instances of the course. Cause other students have the same courses.
studentid = input("enter studentid")
course = input("enter the course to delete")
with open("studentDatabase.dat") as file:
f = file.readlines()
with open("studentDatabase.dat","w") as file:
for line in lines:
if line.find(course) == -1:
file.write(line)
This just deletes the whole line but I only want to delete the course
Welcome to the site. You have a little ways to go to make this work. It would be good if you put some additional effort in to this before asking somebody to code this up. Let me suggest a structure for you that perhaps you can work on/augment and then you can re-post if you get stuck by editing your question above and/or commenting back on this answer. Here is a framework that I suggest:
make a section of code to read in your whole .dat file into memory. I would suggest putting the data into a dictionary that looks like this:
data = {1001: (name, email, <whatever the digits stand for>, [SRT111, OPS333, ...],
1044: ( ... )}
basically a dictionary with the ID as the key and the rest in a tuple or list. Test that, make sure it works OK by inspecting a few values.
Make a little "control loop" that uses your input statements, and see if you can locate the "record" from your dictionary. Add some "if" logic to do "something" if the ID is not found or if the user enters something like "quit" to exit/break the loop. Test it to make sure it can find the ID's and then test it again to see that it can find the course in the list inside the tuple/list with the data. You probably need another "if" statement in there to "do something" if the course is not in the data element. Test it.
Make a little "helper function" that can re-write a data element with the course removed. A suggested signature would be:
def remove_course(data_element, course):
# make the new data element (name, ... , [reduced course list]
return new_data_element
Test it, make sure it works.
Put those pieces together and you should have the ingredients to change the dictionary by using the loop and function to put the new data element into the dictionary, over-writing the old one.
Write a widget to write the new .dat file from the dictionary in its entirety.
EDIT:
You can make the dictionary from a data file with something like this:
filename = 'student_data.dat'
data = {} # an empty dictionary to stuff the results in
# use a context manager to handle opening/closing the file...
with open(filename, 'r') as src:
# loop through the lines
for line in src:
# strip any whitespace from the end and tokenize the line by ":"
tokens = line.strip().split(':')
# check it... (remove later)
print(tokens)
# gather the pieces, make conversions as necessary...
stu_id = int(tokens[0])
name = tokens[1]
email = tokens[2]
some_number = int(tokens[3])
# splitting the number from the list of courses is a little complicated
# you *could* do this more elegantly with regex, but for your level,
# here is a simple way to find the "chop points" and split this up...
last_blobs = tokens[4].split('[')
course_count = int(last_blobs[0])
course_list = last_blobs[1][:-1] # everything except the last bracket
# split up the courses by comma
courses = course_list.split(',')
# now stuff that into the dictionary...
# a little sanity check:
if data.get(stu_id):
print(f'duplicate ID found: {stu_id}. OVERWRITING')
data[stu_id] = (name,
email,
some_number,
course_count,
courses)
for key, value in data.items():
print(key, value)
i got something for you. What you want to do is to find the student first and then delete the course: like this.
studentid = input("enter studentid")
course = input("enter the course to delete")
with open("studentDatabase.dat") as file:
f = file.readlines()
with open("studentDatabase.dat","w") as file:
for line in lines:
if studentid in line: # Check if it's the right sudent
line = line.replace(course, "") # replace course with nothing
file.write(line)
You want to check if we are looking at the correct student, then replace the line but without the course code. Hope you can find it useful.

Need multiple inputs saved to another single input, all information given by user

Building a webscraper for a game I love and right now came into a little issue with python, what I want to do could best be show as:
userdata = { ' ', [ ]}
I'm new to writing python so my question is would this work given the following scenario:
User's account name (which players in the game use to message each other) wants to attach multiple character names to that single account name so other players know that all these characters belong to that one account.
The end result should be something like this:
"Please enter your account name followed by which characters you wish associated with this account:"
user input: Leafzer Leaf1 Leaf2 Leaf3
current limitations in the game work to python's advantage as account and character names can not have any white space. I was considering using split such as:
x = [str(x) for x in input("Enter user data: ").split()]
but as it stands neither of these seem to work quite right.
To reiterate and maybe clear some of the confusion: Writing a website scraper that allows players in the game to enter their account name and a list of mules (characters in the game that just hold items). The list of mules and the account name must be separate as my scraper uses the list of mules to go to a certain website using that mule name and downloads the data into a searchable csv file. If another player searches for an item that is within that csv file, it brings up the account name associated with the mule rather than the mule name and displays the account name to player searching for the item.
I'm stuck trying to figure out how to obtain the user data in this manner. Any help would be appreciated.
Are you after something like this:
users = {}
user, *chars = input("Please input your name and characters: ").split(" ")
users[user] = chars
?
Or slightly less confusingly (but not nearly as neatly):
users = {}
words = input("Please input your name and characters: ").split(" ")
user = words[0]
chars = words[1:]
users[user] = chars
But * unpacking is great, and everyone should use it!
P.S. for your second use case, just call input() twice!:
username = input("Please input your name: ")
chars = input("Please input your characters: ").split(" ")

Remove certain lines in an external textfile

I'm working on a program which should be able to handle basic library tasks. I've a
problem with a class method which is suppose to offer the user the possibility to remove a certain book from the library. The list of books is contained on an external textfile with the following format (author, title):
Vibeke Olsson, Molnfri bombnatt
Axel Munthe, Boken om San Michele
The metod I'm using is shown below:
def removeBook(self):
removal_of_book = input("What's the book's titel, author you'd like to remove?: ")
with open("books1.txt" , "r+") as li:
new_li = li.readlines()
li.seek(0)
for line in new_li:
if removal_of_book not in line:
li.write(line)
li.truncate()
print(removal_of_book + " is removed from the system!")
The problem with this method is it that every row containing removal_of_book gets removed (or not rewritten on the file). I know that the method is far from optimal and probably should be scratched but I'm completely lost in finding an alternative.
Does anyone have a better solution to this problem?
You can create your lines to write into the new file on the fly using a list comprehension and then write them to the new file afterwards (using the same file name to overwrite the original file):
def removeBook(self):
to_remove = input("What's the book's title, author you'd like to remove?: ")
with open("books1.txt" , "r+") as li:
new_li = [line for line in li.readlines() if to_remove not in line]
new_file = open('books1.txt', 'w'); new_file.write(new_li); new_file.close()
print(to_remove + " is removed from the system!")
Note that string membership checking is case sensitive, so you are expecting your user to match your case in the original file exactly. You might think about converting the strings to lower-case prior to performing your check using lower().

Python giving list out of bounds but it shows both elements in the list [duplicate]

This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 7 months ago.
I'm trying to make a simple log in program using python (still fairly new to it), and I have the log in information stored in a text file for the user to match in order to successfully log in. Whenever I run it it says "list index out of range" but I'm able to print out the value of that element in the list, which is where I'm confused. I am trying to add the first line (username) and the second line (password) in the file to the list to compare to the user inputted values for each field, but am unable to compare them.
def main():
username = getUsername()
password = getPassword()
authenticateUser(username, password)
def getUsername():
username = input("Please enter your username: ")
return username
def getPassword():
password = input("Please enter your password: ")
return password
def authenticateUser(username, password):
credentials = []
with open("account_information.txt") as f:
content = f.read()
credentials.append(content)
if(username == credentials[0] and password == credentials[1]):
print("Login Successful!")
else:
print("Login Failed")
main()
You should use readline to get your infos in a list :
def authenticateUser(username, password):
credentials = []
with open("account_information.txt") as f:
content = f.readlines()
Using this, accordingly to what you describe, content[0] will be your username and content[1] your password.
Depending on what is in your account_information.txt, file.read might not be the function you want to use.
Indeed, read will return a string, that is a list of all the characters in the file. So if you have your username and password on two separate lines for instance
foo
H0weSomeP4ssworD
you may instead use readlines to parse your file into a list of strings where each element is a line within the file.
If you look at the python documentation at 7.2.1. Methods of File Objects, you'll see
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string or bytes object
You will see that f.read() is not the function you are looking for. try f.readlines() instead to put the content in a list of lines.
If you want to read all the lines of a file in a list you can also use list(f) or f.readlines().
After having "your problem solved", I invite you to come back to your problem description:
Python giving list out of bounds but it shows both elements in the list
What have you learned besides the fact that you have used the wrong method? I hope also something about your diagnostic skills. How should you print out a list to see how many items it contains?
If you do it like this
items = []
items.append("hello\nworld")
for i in items:
print(i)
you'll see:
hello
world
If you therefore deduce to have 2 items in the list, is this correct?
And python definitely reports that you're accessing the list out of bounds. You saw the conflict between your and python's perspective.
I think you should at least have learned using len() for out-of-bounds diagnostics today.

removing duplicate strings from the list?

I wrote a program to extract all email addresses from a text file starting from 'From:'.I created a list to store all extracted email addresses into list and create another list to store only unique email addresses by removing duplicate email addresses. Now I am getting the output but at the same time I am getting output which shows 'set'before printing the new list i.e after "print Unique_list"
Note - original text file is not attached as I dont know how to do it.
Thank you
print "Please enter the file path:\n"
text_file = raw_input ("Enter the file name:")
print "Opening File\n"
#Using try and except to print error message if file not found
try:
open_file = open ( text_file )
print "Text file " + text_file + " is opened \n"
except:
#Printing error message
print "File not found"
#Using "raise SystemExit" for program termination if file not found
raise SystemExit
#Creating dynamic list to store the no. Email addresses starting from 'From:'
Email_list = [];
#Using loop to extract the Email addresses starting from 'From:'
for line in open_file:
if 'From:' in line:
#Adding each extracted Email addresses at the end of the list
Email_list.append(line)
print "Printing extracted Email addresses\n"
print Email_list,"\n"
print "Before removing duplicate Email addresses, the total no. of Email addresses starting with 'From:'",len(Email_list),"\n"
#Removing duplicate Email addresses
Unique_list = set(Email_list)
#print Email_list.count()
print "Printing Unique Email addresses\n"
print (Unique_list)
print "After removing duplicate Email addresses, the total no. of Email [enter image description here][1]address starting with From:, ",len(Unique_list),"\n" )`
getting output which shows 'set'before printing the new list i.e after "print Unique_list"
Just convert it back to a list again.
Unique_list = set(Email_list)
Unique_list = list(Unique_list)
#print Email_list.count()
print "Printing Unique Email addresses\n"
print (Unique_list)
The answer may depend on the goal. It is not clear based on the question whether the goal is exclusively to print the addresses in a specific way; or to print them according to some assumptions of readability. If the goal is to print in a given desired way, you may be well-served by controlling the output; rather than relying on the built-in String representation of the objects that you would be printing.
An example:
Instead of print Email_list,"\n"
use print print (','.join (Email_list, '\n'))
If you would like to emulate the representation of a list, you could use something like print ('[\'{list}\']'.format (list = '\', \''.join (Email_list)), '\n')
or maybe something more cohesive.
In any case, you could control the way in which you would like to print.
If you rely on internally-determined representations of objects for printing, you may be pushed to make coding considerations based on questions of output; and this is not a choice that supports one's ability to make the best coding choices for pure program logic.
Or, did I misunderstand your question?

Categories