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.
Related
I want to create a list from one line in a file, but I cannot find a way on how to do it, does anybody have any tips on how to do it?
"text.txt file"
22 21 20
And this is my latest attempt to do it, but the list is not split into three elements, but instead is one whole string.
f = open("file.txt")
line = f.readline()
line = line.replace(" ", ", ")
list1 = [line]
print(list1)
Output:
['22, 21, 20']
Use split() to split the string into a list of strings. If you want to turn those strings into ints, call int on each one.
with open("file.txt") as f:
list1 = f.readline().split()
print(list1) # ['22', '21', '20']
print([int(n) for n in list1]) # [22, 21, 20]
you can use this:
with open("tasks.txt", 'r') as data:
data=[int(each_int) for ele in data.readlines() for each_int in ele.split() ]
print(data)
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:
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)
Is it possible to write into file string without quotes and spaces (spaces for any type in list)?
For example I have such list:
['blabla', 10, 'something']
How can I write into file so line in a file would become like:
blabla,10,something
Now every time I write it into file I get this:
'blabla', 10, 'something'
So then I need to replace ' and ' ' with empty symbol. Maybe there is some trick, so I shouldn't need to replace it all the time?
This will work:
lst = ['blabla', 10, 'something']
# Open the file with a context manager
with open("/path/to/file", "a+") as myfile:
# Convert all of the items in lst to strings (for str.join)
lst = map(str, lst)
# Join the items together with commas
line = ",".join(lst)
# Write to the file
myfile.write(line)
Output in file:
blabla,10,something
Note however that the above code can be simplified:
lst = ['blabla', 10, 'something']
with open("/path/to/file", "a+") as myfile:
myfile.write(",".join(map(str, lst)))
Also, you may want to add a newline to the end of the line you write to the file:
myfile.write(",".join(map(str, lst))+"\n")
This will cause each subsequent write to the file to be placed on its own line.
Did you try something like that ?
yourlist = ['blabla', 10, 'something']
open('yourfile', 'a+').write(', '.join([str(i) for i in yourlist]) + '\n')
Where
', '.join(...) take a list of strings and glue it with a string (', ')
and
[str(i) for i in yourList] converts your list into a list of string (in order to handle numbers)
Initialise an empty string j
for all item the the list,concatenate to j which create no space in for loop,
printing str(j) will remove the Quotes
j=''
for item in list:
j = j + str(item)
print str(j)
Say I have a text file formatted like this:
100 20 the birds are flying
and I wanted to read the int(s) into their own lists and the string into its own list...how would I go about this in python. I tried
data.append(map(int, line.split()))
that didn't work...any help?
Essentially, I'm reading the file line by line, and splitting them. I first check to see if I can turn them into an integer, and if I fail, treat them as strings.
def separate(filename):
all_integers = []
all_strings = []
with open(filename) as myfile:
for line in myfile:
for item in line.split(' '):
try:
# Try converting the item to an integer
value = int(item, 10)
all_integers.append(value)
except ValueError:
# if it fails, it's a string.
all_strings.append(item)
return all_integers, all_strings
Then, given the file ('mytext.txt')
100 20 the birds are flying
200 3 banana
hello 4
...doing the following on the command line returns...
>>> myints, mystrings = separate(r'myfile.txt')
>>> print myints
[100, 20, 200, 3, 4]
>>> print mystrings
['the', 'birds', 'are', 'flying', 'banana', 'hello']
If i understand your question correctly:
import re
def splitList(list):
ints = []
words = []
for item in list:
if re.match('^\d+$', item):
ints.append(int(item))
else:
words.append(item)
return ints, words
intList, wordList = splitList(line.split())
Will give you two lists: [100, 20] and ['the', 'birds', 'are', 'flying']
Here's a simple solution. Note it might not be as efficient as others for very large files, because it iterates over word two times for each line.
words = line.split()
intList = [int(x) for x in words if x.isdigit()]
strList = [x for x in words if not x.isdigit()]
pop removes the element from the list and returns it:
words = line.split()
first = int(words.pop(0))
second = int(words.pop(0))
This is of course assuming your format is always int int word word word ....
And then join the rest of the string:
words = ' '.join(words)
And in Python 3 you can even do this:
first, second, *words = line.split()
Which is pretty neat. Although you would still have to convert first and second to int's.