I have a very simple program to sort data and write it to a text file, but the sorted method is not doing what it should be. Instead the values are entering the array and text file in the order I input them. Can anyone quickly explain why?
import os
import os.path
values = []
#for value in values:
data = 1
while data:
data = input('Enter the values. Press enter to confirm values:')
if data:
values.append(data)
else:
data = data
print(sorted(values))
sort = sorted(values)
print(sort)
name = open("sortedvalues.txt", "a+") #opens file usernames.txt and gets ready to write to it
file = str(sort) #converts the values to a string and writes them to the file
name.write('\n' + file) #writes contents in file to usernames.txt
name.close() #closes file
open1 = open("sortedvalues.txt", "r") #opens file to read it
print('reading')
print (open1.read()) #prints whatever is in the text file
I could not recreate your issue. The below code is works fine, sorts the given bunch of numbers correctly and writes to file.
Also you are sorting array twice, I just corrected it.
values = []
sorted_values = []
data = 1
while data:
data = input('Enter the values. Press enter to confirm values:')
if data:
values.append(data)
else:
data = data
# here you are sorted it first and second outside of while loop
sorted_values = sorted(values)
print(sorted_values)
print(sorted_values)
with open("sortedvalues.txt", "a+") as name:
name.write('\n' + str(sorted_values))
with open("sortedvalues.txt", "r") as open1:
print('reading')
print (open1.read())
inputs:
5
3
4
2
1
0
inside file:
[1, 2, 3, 4, 5]
#JohnGordon answered the question in a below comment. The issue was not with the way the code was working, as improper as it may be. The problem is that the integer values are actually being taken as strings and sorting as if they were strings. The input values first need to be converted before being sorted.
Edit I should add that specifying the input as an integer results in a traceback because null (when the user presses enter to confirm the entered values) can not be parsed as an integer. To work around this, I simply added
while data:
data = input('Enter the values. Press enter to confirm values:')
if data:
values.append(int(data))
else:
data = data
print(sorted(values))
Specifically, in the if data:portion, specifying to append data as an int to the list solves the problem and the sorted or .sort() methods work correctly.
Related
I have a code that generates characters from 000000000000 to ffffffffffff which are written to a file.
I'm trying to implement a check to see if the program was closed so that I can read from the file, let's say at 00000000781B, and continue for-loop from the file.
The Variable "attempt" in (for attempt in to_attempt:) has tuple type and always starting from zero.
Is it possible to continue the for-loop from the specified value?
import itertools
f = open("G:/empty/last.txt", "r")
lines = f.readlines()
rand_string = str(lines[0])
f.close()
letters = '0123456789ABCDEF'
print(rand_string)
for length in range(1, 20):
to_attempt = itertools.product(letters, repeat=length)
for attempt in to_attempt:
gen_string = rand_string[length:] + ''.join(attempt)
print(gen_string)
You have to store the value on a file to keep track of what value was last being read from. I'm assuming the main for loop running from 000000000000 to ffffffffffff is the to_attempt one. All you need store the value of the for loop in a file. You can use a new variable to keep track of it.
try:
with open('save.txt','r') as reader:
save = int(reader.read())
except FileNotFoundError:
save = 0
#rest of the code
for i in range(save,len(to_attempt)):
with open('save.txt','r') as writer:
writer.write(i)
#rest of the code
Currently, my issue is that I have created a function that takes in a single hash input that is a hash of a number from 1 to 500000. However, I cannot figure out how to input a list into this function which the for loop will out put the list of the "unhashed" values for me which in this case would be numbers.
So for example:
I put in the hash for
"2" = "d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35"
and then, I run my code which compares it to my library, and it checks if it is the same to a hashed value in my libary and if it is, it will output 2 in this case.
I am not sure where to start from. I tried changing the password into an empty matrix to house the values, but that did not work.
import hashlib
counter = 1
#C:\Users\valov\Desktop #location of wordlist file
try:
sha256_file = open("C:/Users/valov/Desktop/lab3.txt",'r')
except:
print("\nFile Not Found")
quit()
#sha256_file = open(r"C:/Users/valov/Desktop/lab3.txt", 'r') #read file
def hash_to_int(hash_list):
global counter
#for loop to go through given file and then encode hash
for password in sha256_file:
hash_obj = hashlib.sha256(password.strip().encode('utf-8')).hexdigest()
(counter,password.strip())
counter += 1
#check inserted hash against hash from our file, if true, print out value
if hash_obj == hash_list:
print(password)
However, I cannot make it take in a list. So if I input the hash of 1 and 2 together like this:
hash_to_int(["6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b"
"d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35"])
it will output [1 2]
I am running with some issue. I will like to view the number of times a user has delete a value from a key even if the user exits the program, it will still retain that number. So that in future if the user will to delete any values again, it will use the existing number and add on from there.
edited: Just to add. All the dict will be store on a .txt file
dict= {} #start off with an empty list
key_search = ("Enter to find a key")
if options_choose == 2:
c = input('Which value would you like to change? ')
c = change.lower()
if change in list_of_value:
loc = list_of_value.index(c)
list_of_value.remove(c)
correction = input("Enter correction: ")
correction = correction.lower()
print(f"value(s) found relating to the key '{key_search}' are:")
list_of_value.insert(loc, correction)
list_of_value = dict[key_search]
for key, value in enumerate(list_of_value, 1):
print(f"{key}.) {value}")
else:
print('Entry invalid')
As you can see in the below screenshot I have exited and re-entered the program with the same counter.
You can adapt this to fit the features of your program. Since it seems like the code you provided is incomplete, I have substituted it with an example of dictionary modification to show how you can store and read a value after program termination.
You have to have a folder with test.py and modification.value.txt inside. Write "0" inside the text file.
ex_dict= {'example_entry':1}
#Read in the value stored into the text file.
with open('modification_value.txt','r') as file:
counter = int(file.readline()) #counter value imported from file.
print('Counter: ', counter)
modify_dict = True #boolean to check when user wants to stop making changes
while modify_dict == True:
for key in ex_dict:
dict_key = key
new_value = input('Enter value for new key.\n')
ex_dict[dict_key] = new_value
counter+=1
print('New dictionary: ', ex_dict, '\n')
response = input("Do you still want to modify Y/N?\n")
if (response =='Y'):
continue
elif(response =='N'):
modify_dict=False
#Write the value of the counter recorded by the program to the text file so the program can access it when it is run again after termination.
with open('modification_value.txt','w+') as file:
file.write(str(counter))
I cannot seem to find the input value in the csv file and only display the rows containing the input value.
The alignment of the csv data with the printed headers is also an issue I am struggling to solve.
import csv
def menu():
print("Menu") #Prints menu page to select option
print("======")
print("[1]: Display info")
print("[0]: Exit")
def info():
read = csv.reader(open("value.csv", "r"))
for j in read:
print(j[:4])
while True:
menu()
selection = int(input("Enter your selection: ")) #Choose selection from menu
if selection == 1:
print("1: Display info")
print()
Num = str(input("Enter a value.: ")) #Input value to find for match, refers to the Value in value.csv file
print("{:<10}{:<15}{:<15}{:<11}".format("Value", "Time", "Distance", "Pace")) #Prints heading
print("{:<10}{:<15}{:<15}{:<11}".format("--------", "-------------", "-------------", "---------")) #Prints heading with alignment
info() #Executes def function
elif selection == 0:
break #Exit from program
could you use the following code?
finder.py
import csv
from collections import OrderedDict
tofind = input("String to find:")
print("{:<10}{:<10}".format("Index", "Value"))
with open('data.csv', 'r') as csvfile:
content = csv.reader(csvfile, delimiter=',')
for index, value in content:
if ( value == tofind ):
print("{:<10}{:<10}".format(index, value))
data.csv
1,test
2,ok
3,findme
4,test
5,random
6,findme
7,findme
8,no
9,yes
10,findme
Output
➜ python python3 finder.py
String to find:yes
Index Value
9 yes
➜ python python3 finder.py
String to find:findme
Index Value
3 findme
6 findme
7 findme
10 findme
HTH
Your formatting problem is simple to solve.
Your code formats your headings like this:
print("{:<10}{:<15}{:<15}{:<11}".format("Value", "Time", "Distance", "Pace"))
but the function that prints the data does no formatting at all:
print(j[:4])
If you want the data to line up with the headings you need to format it that way:
print("{:<10}{:<15}{:<15}{:<11}".format(*j[:4]))
Though it is usual to have numbers, and the column headings above them, right-aligned not left-aligned (> not <), and my personal preference is to centre dates and times (^ not <).
COLDSPEED has already answered your other question. The function info() lists everything in the .csv file. If you want to filter on the value of Num then you need to pass Num to the info() function and perform an if-test in that function to select the data the user wants to see.
We can't tell what that if-test should be. Is Num supposed to be a value in the file (if so, which one? distance, maybe?), or what? In other words, on what basis do you want the selection to happen? That needs to be in your question if you want an answer.
Simple question: i've got this code:
i want to fetch a row with Dictreader from the csv package, every entry i wanto to cast it float and put it in the data array. At the end of the scanning i want to print the first 10 elements of the array. It gives me error of visibility on the array data.
with open(train, "r") as traincsv:
trainreader = csv.DictReader(traincsv)
for row in trainreader:
data = [float(row['Sales'])]
print(data[:10])
If i put the print inside the for like this
with open(train, "r") as traincsv:
trainreader = csv.DictReader(traincsv)
for row in trainreader:
data = [float(row['Sales'])]
print(data[:10])
It prints all the entries not just 10.
You are overwriting data every time in the for loop. This is the source of your problem.
Please upload an example input for me to try and I will, but I believe what is below will fix your problem, by appending to data instead of overwriting it.
Also, it is good practice to leave the with block as soon as possible.
# Open with block and leave immediately
with open(train, "r") as traincsv:
trainreader = csv.DictReader(traincsv)
# Declare data as a blank list before iterations
data =[]
# Iterate through all of trainreader
for row in trainreader:
data.append([float(row['Sales'])])
# Now it should print first 10 results
print(data[:10])
Ways of appending a list:
data = data + [float(row['Sales'])]
data += [float(row['Sales'])]
data.append([float(row['Sales'])]