Storing data from a text file to a dictionary with keys - dictionary

branching off from my previous question. How can i import data from a text file and then store it in a dictionary with a specific key such as:
there is a space between each username and password but they appear directly below each other on text file
Text file:
username,password
user2,password2
user3,password3
into a dictionary in python as follows:
Database = {username: password,user2: password2,user3: password3}
which i can then use in a log in validificator to confirm wheter both username and password is correct

So you have a user/pwd pair per line? You can loop through the lines of your files and split with ,:
db = {}
with open("file.txt", "r") as f:
for l in f.readlines():
words = l.strip().split(',')
if len(words) > 1: # only considering lines with at least one comma
db[words[0]] = words[1]

Related

Query is unable to match parts after "/" or parts within "()" in the data

I have a search request written as
import sqlite3
conn = sqlite3.connect('locker_data.db')
c = conn.cursor()
def search1(teacher):
test = 'SELECT Name FROM locker_data WHERE Name or Email LIKE "%{0}%"'.format(teacher)
data1 = c.execute(test)
return data1
def display1(data1):
Display1 = []
for Name in data1:
temp1 = str(Name[0])
Display1.append("Name: {0}".format(temp1))
return Display1
def locker_searcher(teacher):
data = display1(search1(teacher))
return data
This allows me to search for the row containing "Mr FishyPower (Mr Swag)" or "Mr FishyPower / Mr Swag" with a search input of "FishyPower". However, when I try searching with an input of "Swag", I am then unable to find the same row.
In the search below, it should have given me the same search results.
The database is just a simple 1x1 sqlite3 database containing 'FishyPower / Mr Swag'
Search Error on 'Swag'
Edit: I technically did solve it by limiting the columns being searched to only 'Name' but I intended the code search both the 'Name' and 'Email' columns and output the results as long as the search in within either or both columns.
Edit2: SELECT Name FROM locker_data WHERE Email LIKE "%{0}%" or Name LIKE "%{0}%" was the right way to go.
I'm gonna guess that Mr. FishyPower's email address is something like mrFishyPower#something.com. The query is only comparing Email to teacher. If it was
WHERE Name LIKE "%{0}%"
OR Email LIKE "%{0}%"'
you would (probably) get the result you want.

Python-3.6 - "Not In List" Error

I'm using Python 3.6.3.
I am trying to validate a username and password from a csv file. The usernames and subsequent passwords are on new lines in the text file, so when appended to an empty array I called "up" it was turned into a 2d array with each line a list within "up". I ask the user for a username and a password. So then I tried to use a for loop (for x in up) to loop over each list in up via up[up.index(x)], and then used .index(username) straight afterwards in a variable called j (j = up[up.index(x)].index(username)). The code will be given, with the section I'm having trouble with highlighted.
These are the contents of the csv file: Text File
When I run the code the it returns an error that says the username in not in the list. I've searched for answers but couldn't find anything. Is there something that I've overlooked?
Any help will be gratefully appreciated.
import csv
validoption = ["i","u"]
while True:
option = input("Sign in or sign up\nPlease enter 'i' to sign in or 'u' to sign up: ")
if option in validoption:
if option is "i":
with open("login.txt","r") as l:
up = []
read = csv.reader(l)
count = 0
for line in read:
up.append(line)
count=+1
invalid = True
while invalid:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
if [[y is username for y in x] for x in up]:
for x in up:
j = up[up.index(x)].index(username)
if password in up[up.index(x)][j+1]:
invalid = False
else:
print("Password is incorrect")
else:
print("Username is not recognised")
else:
with open("login.txt","a") as l:
username = input("Please enter your username: ")
while True:
password = input("Please enter your password\nPlease make sure that your password is longer than 8 characters, has a capiatal letter and a number: ")
if len(password)<8:
if any(p.isupper() for p in password):
if any(p.isdigit() for p in password):
break
else:
print("Password must have one number in it\n")
else:
print("Password must have one capital letter\n")
else:
print("Password must have more than 8 charaters")
userdetails = username+","+password
l.write(userdetails)
l.write("\n")
Thank you :)
y is username tests if the two values are the same object, not equivalent objects. Use == instead.
Additionally, you should consider using the username as the key of a dict, then you can use in and eliminate some of the loops in your application code.

Looping through XMLReader to replace special characters in data field

I have XML files I want to put into data sets to export to a database using VB.Net. There is a possibility that new XML files added to this list daily will have special characters (idk why anyone would include "&" in an address entry anyway). After creating the XMLReader, what is the easiest way to replace the escape characters? What would the pseudo code look like? Stream Reader maybe? Or does that work with XMLReader?
Here is my code right now that attempts the data set creation:
For Each file1 In Directory.GetFiles(My.Settings.Local_Meter_Path, "*BadMeter*.xml")
Dim filecreatedate As String = IO.File.GetLastWriteTime(file1)
FN = Path.GetFileName(file1).ToString()
xmlFile = XmlReader.Create(Path.Combine(My.Settings.Local_Meter_Path, FN), New XmlReaderSettings())
ds.ReadXml(xmlFile)
and the spot where I'm getting ampersand entity-name parsing error
<Cell ss:StyleID="Default"><Data ss:Type="String">1440 COUNTY ROAD 40 X-MAS LIGHT & RV #2 CAMP HILL</Data></Cell>

Storing string variable contains with comma and new line as value to CSV in R

i am trying to save this two objects into a csv file , this i used inside function that is why i used append write.table
dt <- "Error in .verify.JDBC.result(r, \"Unable to retrieve JDBC result set for \", : \n Unable to retrieve JDBC result set for SELECT * FROM rAXA (ORA-00942: table or view does not exist\n)\n"
er <- "error"
er_file <- cbind(er,dt)
write.table(er_file, file = "E:\\Hama_Hex\\Project\\Predictive\\log1.csv",sep=",",
col.names = FALSE, append=TRUE)
but when i execute the above script its not properly saving into csv file, the special character \n in dt object is creating problem , it making to move new line . i want to store entire line in one cell. Here i am saving in csv format, value has some comma so it got splits and enter into new cell.
You just need to escape the newline characters:
write.table(gsub("\\n", "\\\\n", er_file),
file = "E:\\Hama_Hex\\Project\\Predictive\\log1.csv",sep=",",
col.names = FALSE, append=TRUE)
This will replace every \n with \\n. Note in the above code that you have to escape the \ characters in order to create a usable regular expression for gsub.

CSV file (with special characters) upload encoding issue

I am trying to upload a CSV file that has special characters using ServletFileUpload of apache common. But the special characters present in the CSV are being stored as junk characters in the database. The special characters I have are Trademark, registered etc. Following is the code snippet.
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value "
+ Streams.asString(stream, "UTF-8") + " detected.");
}
}
I have tried reading it using BufferendReader, used request.setCharacterEncoding("UTF-8"), tried upload.setHeaderEncoding("UTF-8") and also checked with IOUtils.copy() method, but none of them worked.
Please advice how to get rid of this issue and where it needs to be addressed? Is there anything I need to do beyond servlet code?
Thanks
What database are using? What character set is database using? Characters can be malformed in the database rather than in Java code.

Resources