I have a function called new_safe() and I made a lst with new safe numbers. Now I need to read the sae.txt file with a for loop. Every number that is in safe.txt needs to be deleted from the lst I made.
def nieuwe_kluis():
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
for lijst in lst:
print(lijst)
file = open('kluizen.txt', 'r')
for line in file:
if lst == file:
lst.remove(file)
print(line)
You get the lines from the file, but you use file in the comparison and the remove rather than line.
You also don't check if the line (which I assume is one number per line) is a number within the list. Instead you just try to compare the list itself.
Assuming that each line in the file contains one number, you should try something along the lines of
for line in file:
number = int(line)
if number in lst:
lst.remove(number)
print(line)
Related
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 10 days ago.
Hi hope everyone is okay.
I am trying to find the most simple method to take data from a text file and store it into diffrent
variables. Below is the format of a text file:
TEXT FILE:
min:1,2,3,4,5,7,8,9
avg:1,2,3,4
max:1,2,3,4,5,1,2,3,44,55,32,12
I want to take each of these lines remove the part before the number starts (min,avg,max and the ':')
and store all the number data in seperate variables in their appropriate names.
NOTE: amount of numbers in each line may differ and shouldnt effect the code
desired in python:
min = [1,2,3,4,5,7,8,9]
avg = [1,2,3,4]
max = [1,2,3,4,5,1,2,3,44,55,32,12]
The code i have tried:
with open('input.txt', 'r') as input:
input = input.read()
input = input.strip().split(',')
After this part i am unsure which method would be best to achieve what I am trying to do.
Any help is appriciated!
There's no reasonable way to generate variables (by name) dynamically. Better to use a dictionary. Something like this:
my_dict = {}
with open('input.txt') as data:
for line in map(str.strip, data):
try:
key, vals = line.split(':')
my_dict[key.rstrip()] = list(map(int, vals.split(',')))
except ValueError:
pass
print(my_dict)
Output:
{'min': [1, 2, 3, 4, 5, 7, 8, 9], 'avg': [1, 2, 3, 4], 'max': [1, 2, 3, 4, 5, 1, 2, 3, 44, 55, 32, 12]}
Using exec for a string evaluation. Do that on trusted data to avoid injection attacks.
with open('input.txt', 'r') as fd:
data = fd.read()
# list of lines
lines = data.split('\n')
# python code format
code_format = '\n'.join("{} = [{}]".format(*line.partition(':')[::2]) for line in lines if line)
# execute the string as python code
exec(code_format)
print(avg)
#[1, 2, 3, 4]
Notice that there is a further side effect in this code evaluation since some variable identifiers overload those of the built-in functions min, max. So, if after the execution of the code you try to call such build-in functions you will get TypeError: 'list' object is not callable.
One way to re-approach the problem would be by pickling the objects and use pickle.dumps to save an object to a file and pickle.loads to retrieve the object, see doc.
This is how you store it in a python dictionary:
txtdict = {}
with open('input.txt', 'r') as f:
for line in f:
if line.strip():
name = line.split(':')[0]
txtdict[name] = [int(i) for j in line.strip().split(':')[1:] for i in j.split(',')]
Output:
{'min': [1, 2, 3, 4, 5, 7, 8, 9],
'avg': [1, 2, 3, 4],
'max': [1, 2, 3, 4, 5, 1, 2, 3, 44, 55, 32, 12]}
I have a text file that reads the following and is called split.txt:
18, 1, 3, 4, 35
42, 6, 9, 12, 24
2, 22, 45, 91, 75
I want to print ONLY the last number in each line and I did that by doing this:
with open("split.txt", "rt") as split:
for line in split:
print (line.strip()[-2:])
How would I edit my code so that I am able to print ONLY the number that are greater than 50? So I'm not sure how to make an if statement to output my desired results.
Thanks in advance!
You get each line as variable line in the loop, split it with a comma, and get the last item with indexing at [-1]. Assuming it will always be a number, cast it to int. The strip() won't be absolutely necessary as int(' 23 ') will still be an integer 23.
with open("split.txt", "rt") as split:
for line in split:
last_number = int(line.split(',')[-1].strip())
if last_number > 50:
print(last_number)
I'm pretty new to python. I'm trying to define a function to read from a given file and count the number of words in each line and output the result as a list.
Here's my code:
def nWs(filename):
with open(filename,'r') as f:
k=[]
for line in f:
num_words=0
words=line.split()
num_words +=len(words)
k.append(num_words)
print (k)
print( nWs('random_file.txt') )
The expected output is something like:
[1, 22, 15, 10, 11, 13, 10, 10, 6, 0]
But it returns:
[1, 22, 15, 10, 11, 13, 10, 10, 6, 0]
None
I don't understand why this term None is returned. There's nothing wrong with the text file, its just random text and I'm only trying to print words in 1 file. So I don't understand this result. Can anyone explain why? And also how can I get rid of this None term.
I assume the indenting is correct when you tried to run it as it wouldn't run otherwise.
The None is the result of you calling the function in the print statement. Because nWs doesn't return anything, the print statement prints None. You could either call the function without the print statement or instead of using print in the function, use return and then print.
def nWs(filename):
with open(filename,'r') as f:
k=[]
for line in f:
num_words=0
words=line.split()
num_words +=len(words)
k.append(num_words)
print (k)
nWs('random_file.txt')
or
def nWs(filename):
with open(filename,'r') as f:
k=[]
for line in f:
num_words=0
words=line.split()
num_words +=len(words)
k.append(num_words)
return k
print(nWs('random_file.txt'))
I am trying to create a database to store the information generated by my code in the form of a 1 x 21 vector. I have called this prices, and would like to store each element of this vector in a new line of a text file. Then, the second time I run the program, I wish to append the new entries of the vector prices onto each respective line in the text file. The purpose of this is so that once a large set of results has been gathered, it is easy to produce a plot to see how each of these 21 elements changed over time.
I tried to copy (with a bit of modification with the condition in the if loop, as well as the overall for loop) the method shown in this answer, but for some reason, I get a blank text file when I run the code. I changed one thing, the w to w+, but it doesn't work with the w either. What am I doing wrong?
prices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1] # this is just a sample output
for exp in range(21):
with open("price_database.txt", 'r') as f:
lines = f.readlines()
with open("price_database.txt", 'w+') as f:
for x, line in enumerate(lines):
if x == exp:
f.write(str(prices[exp]))
f.write(line)
Edit 1:
prices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]
for exp in range(21):
with open("price_database.txt", 'r') as f:
lines = f.readlines()
with open("price_database.txt", 'a') as f:
for x, line in enumerate(lines):
if x == exp:
f.write(str(prices[exp]))
You need to close the file every time you open to read or write results with f.close() but i cant undertand why you use txt file to do this job you should really use csv or even mysql it will be much better
Edited:
Open the file with append mode so you can write at the end:
with open('something.txt', 'a') as f:
f.write('text to be appended')
f.close()
If you want to be a little less careful, then do it this way, it is slightly faster because you don’t have to keep closing.
app = 'append text'
with open('something.txt', 'a') as f:
f.write(app)
f.close()
Im a python noob and I'm stuck on a problem.
filehandler = open("data.txt", "r")
alist = filehandler.readlines()
def insertionSort(alist):
for line in alist:
line = list(map(int, line.split()))
print(line)
for index in range(2, len(line)):
currentvalue = line[index]
position = index
while position>1 and line[position-1]>currentvalue:
line[position]=line[position-1]
position = position-1
line[position]=currentvalue
print(line)
insertionSort(alist)
for line in alist:
print line
Output:
[4, 19, 2, 5, 11]
[4, 2, 5, 11, 19]
[8, 1, 2, 3, 4, 5, 6, 1, 2]
[8, 1, 1, 2, 2, 3, 4, 5, 6]
4 19 2 5 11
8 1 2 3 4 5 6 1 2
I am supposed to sort lines of values from a file. The first value in the line represents the number of values to be sorted. I am supposed to display the values in the file in sorted order.
The print calls in insertionSort are just for debugging purposes.
The top four lines of output show that the insertion sort seems to be working. I can't figure out why when I print the lists after calling insertionSort the values are not sorted.
I am new to Stack Overflow and Python so please let me know if this question is misplaced.
for line in alist:
line = list(map(int, line.split()))
line starts out as eg "4 19 2 5 11". You split it and convert to int, ie [4, 19, 2, 5, 11].
You then assign this new value to list - but list is a local variable, the new value never gets stored back into alist.
Also, list is a terrible variable name because there is already a list data-type (and the variable name will keep you from being able to use the data-type).
Let's reorganize your program:
def load_file(fname):
with open(fname) as inf:
# -> list of list of int
data = [[int(i) for i in line.split()] for line in inf]
return data
def insertion_sort(row):
# `row` is a list of int
#
# your sorting code goes here
#
return row
def save_file(fname, data):
with open(fname, "w") as outf:
# list of list of int -> list of str
lines = [" ".join(str(i) for i in row) for row in data]
outf.write("\n".join(lines))
def main():
data = load_file("data.txt")
data = [insertion_sort(row) for row in data]
save_file("sorted_data.txt", data)
if __name__ == "__main__":
main()
Actually, with your data - where the first number in each row isn't actually data to sort - you would be better to do
data = [row[:1] + insertion_sort(row[1:]) for row in data]
so that the logic of insertion_sort is cleaner.
As #Barmar mentioned above, you are not modifying the input to the function. You could do the following:
def insertionSort(alist):
blist = []
for line in alist:
line = list(map(int, line.split()))
for index in range(2, len(line)):
currentvalue = line[index]
position = index
while position>1 and line[position-1]>currentvalue:
line[position]=line[position-1]
position = position-1
line[position]=currentvalue
blist.append(line)
return blist
blist = insertionSort(alist)
print(blist)
Alternatively, modify alist "in-place":
def insertionSort(alist):
for k, line in enumerate(alist):
line = list(map(int, line.split()))
for index in range(2, len(line)):
currentvalue = line[index]
position = index
while position>1 and line[position-1]>currentvalue:
line[position]=line[position-1]
position = position-1
line[position]=currentvalue
alist[k] = line
insertionSort(alist)
print(alist)