How do I make multiple lists from a file? - python

I am using this code to make labels in tkinter. After clicking on them, the text from list1 changes to text form list2. I want to append the text into the lists from a txt file.
self.list1 = [line.rstrip('\n') for line in open("file.txt", encoding = "utf-8")]
self.list2 = [line.rstrip('\n') for line in open("file2.txt", encoding = "utf-8")]
Do I have to make for each list a single txt file? (How) can I make several lists from just one file?
Thanks

def from_file_to_lists(name,lists): #Where lists[0] = list1, lists[1] = list2 etc
i = 0
for line in open(name, encoding = "utf-8"):
line = line.rstrip('\n')
if "line%s" % (i+1) in line: #if next list in line
i +=1 #go to next list
continue #dont write list name inside the list
lists[i].append(line)
return lists
#How to call
list0 = []
list1 = []
list2 = []
lists = [list0,list1,list2]
lists = from_file_to_lists("file.txt",lists)
Your file.txt should be like
Hello i
am list0
list1
Hello, i am
the second list
list2
i am the last
Your list numbering inside the txt file should start from 0, else change
if "line%s" % (i+1) in line:
to
if "line%s" % (i+2) in line:

Related

How can I get python to read each line in a txt file and make seperate lists?

Say I have a .txt file with some integers.
#txt file called ints.txt
1,3
4
5,6
How can I get python to read each line and make them into separate lists?
The output I'm looking for:
['1','3']
['4']
['5','6']
I tried this code but it only prints the first element of the txt file as a list. I want it to print the subsequent elements too.
x = open("ints.txt", "r")
x = x.readline()
x = x.strip()
x = x.split(" ")
for i in x:
print(x)
Output:
['1','3']
['1','3']
Appreciate the help, my friends :)
Try this:
with open('file/path') as f:
lines = [i.strip().split(',') for i in f.readlines() if i.strip()]
To print the list of lists in each line, do this :
print(*lines, sep='\n')
Try readlines method. Something like that.
with open("ints.txt", "r") as f:
for line in f.readlines():
items = line.split(',')
This will help you
`with open("test.txt", "r") as openfile:
for line in openfile:
new_list = [x for x in line.split(" ")]
print(new_list)

Python: How to I save an extracted data from a list, in a tuple(name,num1,num2)?

I have a file opened, and I'm extracting data from list data. The list data has different names and different numbers for each line in the for loop. How do I save each name and its corresponding nums in a tuple? (name, num1, num2).
fp = open(file_name, 'r')
for line in fp:
line.split('\t')
line = line.split()
name = line[0]
num1 = line[2]
name2 = line[3]
You can use a list comprehension to iterate over the file and create a list of tuples:
with open(file_name, 'r') as fp:
my_tuples = [(l[0], l[2], l[3]) for l in (line.split() for line in fp)]
And if you want names, suggest you make some dicts like:
names = "name", "num1", "num2"
my_dicts = [dict(zip(names, line)) for line in my_tuples]

Creating a program that compares two lists

I am trying to create a program that checks whether items from one list are not in another. It keeps returning lines saying that x value is not in the list. Any suggestions? Sorry about my code, it's quite sloppy.
Searching Within an Array
Putting .txt files into arrays
with open('Barcodes', 'r') as f:
barcodes = [line.strip() for line in f]
with open('EAN Staging', 'r') as f:
EAN_staging = [line.strip() for line in f]
Arrays
list1 = barcodes
list2 = EAN_staging
Main Code
fixed = -1
for x in list1:
for variable in list1: # Moves along each variable in the list, in turn
if list1[fixed] in list2: # If the term is in the list, then
fixed = fixed + 1
location = list2.index(list1[fixed]) # Finds the term in the list
print ()
print ("Found", variable ,"at location", location) # Prints location of terms
Instead of lists, read the files as sets:
with open('Barcodes', 'r') as f:
barcodes = {line.strip() for line in f}
with open('EAN Staging', 'r') as f:
EAN_staging = {line.strip() for line in f}
Then all you need to do is to calculate the symmetric difference between them:
diff = barcodes - EAN_staging # or barcodes.difference(EAN_stagin)
An extracted example:
a = {1, 2, 3}
b = {3, 4, 5}
print(a - b)
>> {1, 2, 4, 5} # 1, 2 are in a but in b
Note that if you are operating with sets, information about how many times an element is present will be lost. If you care about situations when an element is present in barcodes 3 times, but only 2 times in EAN_staging, you should use Counter from collections.
Your code doesn't seem to quite answer your question. If all you want to do is see which elements aren't shared, I think sets are the way to go.
set1 = set(list1)
set2 = set(list2)
in_first_but_not_in_second = set1.difference(set2) # outputs a set
not_in_both = set1.symmetric_difference(set2) # outputs a set

Change the display of a list took from text file

I have this code wrote in Python:
with open ('textfile.txt') as f:
list=[]
for line in f:
line = line.split()
if line:
line = [int(i) for i in line]
list.append(line)
print(list)
This actually read integers from a text file and put them in a list.But it actually result as :
[[10,20,34]]
However,I would like it to display like:
10 20 34
How to do this? Thanks for your help!
You probably just want to add the items to the list, rather than appending them:
with open('textfile.txt') as f:
list = []
for line in f:
line = line.split()
if line:
list += [int(i) for i in line]
print " ".join([str(i) for i in list])
If you append a list to a list, you create a sub list:
a = [1]
a.append([2,3])
print a # [1, [2, 3]]
If you add it you get:
a = [1]
a += [2,3]
print a # [1, 2, 3]!
with open('textfile.txt') as f:
lines = [x.strip() for x in f.readlines()]
print(' '.join(lines))
With an input file 'textfiles.txt' that contains:
10
20
30
prints:
10 20 30
It sounds like you are trying to print a list of lists. The easiest way to do that is to iterate over it and print each list.
for line in list:
print " ".join(str(i) for i in line)
Also, I think list is a keyword in Python, so try to avoid naming your stuff that.
If you know that the file is not extremely long, if you want the list of integers, you can do it at once (two lines where one is the with open(.... And if you want to print it your way, you can convert the element to strings and join the result via ' '.join(... -- like this:
#!python3
# Load the content of the text file as one list of integers.
with open('textfile.txt') as f:
lst = [int(element) for element in f.read().split()]
# Print the formatted result.
print(' '.join(str(element) for element in lst))
Do not use the list identifier for your variables as it masks the name of the list type.

Merging 2 lists and remove double entries

I have a piece of code that loads up 2 lists with this code:
with open('blacklists.bls', 'r') as f:
L = [dnsbls.strip() for dnsbls in f]
with open('ignore.bls', 'r') as f2:
L2 = [ignbls.stip() for ignbls in f2]
dnsbls contains:
list1
list2
list3
ignbls contains
list2
What I want to do is merge dnsbls and ignbls and then remove any lines that appears more than once and print those with "for". I was thinking something like:
for combinedlist in L3:
print combinedlist
Which in the aboe example would print out:
list1
list3
You need to use sets instead of lists:
L3 = list(set(L).difference(L2))
Demonstration:
>>> L=['list1','list2','list3']
>>> L2=['list2']
>>> set(L).difference(L2)
set(['list1', 'list3'])
>>> list(set(L).difference(L2))
['list1', 'list3']
For your purposes you probably don't have to convert it back to a list again, you can iterate over the resulting set just fine.
If ignores are smaller than the blacklists (which is normally the case I think), then (untested):
with open('blacklists.bls') as bl, open('ignore.bls') as ig:
bl_for = (line.strip() for line in bl if 'for' not in line)
ig_for = (line.strip() for line in ig if 'for' not in line)
res = set(ig_for).difference(bl_for)

Categories

Resources