Related
everyone!
I have a simple txt file, with few number in a row (',' is separator)
"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21"
and this code:
num=[]
f = open('sample.txt','r')
for i in f:
num.append(i.split(',')
print(num)
my goal is to get list of items:
['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21']
but i get list i list with 1 item:
[['1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21']]
looking for help
If you only have one line in your file, you don't need to loop over lines. You can assign num directly:
with open('sample.txt','r') as f:
num = f.read().split(',')
This code will work even if you have multiple line to read
num=[]
f=open('input.txt')
for i in f:
for j in (i.split(',')):
num.append(j.replace('\n',''))
print(num)
Explanation line by line steps
1.creating empty list
2.opening file
3.Taking one element from f at a time
4.splitting i which returns list and than taking one item from list as j
5.appending j and if there is newline character in j, than remove \n (this happens when we have to read more than on line)
Use extend, instead of append.
What is the difference between Python's list methods append and extend?
num=[]
f = open('sample.txt','r')
for i in f:
num.extend(i.split(','))
print(num)
could anyone please help me with the following problem. I have a task where I need to sort numbers from a txt file from lowest to highest value. No matter the combination of the numbers or length of text it needs to sort the numbers from lowest to highest.
Any help will really be appreciated.
Text file (input.txt)
min:2,1,4,3,6,5
max:1,2,3,4,5,6
avg:1,2,3,4,5,6
I have written some code as follows but its just arranging the line title alphabeticaly
inputFile = open("input.txt", 'r')
lineList = inputFile.readlines()
lineList.sort()
print (lineList)
for line in lineList:
print(line)
with open('inputcopy.txt', 'a') as f:
for line in lineList:
lineList.sort()
f.write(line)
Thank you for any help
Since you're reading data from file, we have every line as a string. So, you need to use split method in combination int constructor.
This can be achieved using a list comprehension.
for line in lineList:
numbers = [int(item) for item in line.split(':')[1].split(',')]
line.split(':')[1] gives as the string 2,1,4,3,6,5
Another split by comma separator gives us the list of numbers. I used int constructor because after split method we have them like strings.
You could use regex. Note that you need to either convert to int or use a custom function that considers the integer representation
for line in lineList:
sorted_line = sorted(map(int, re.findall(r'\d+',line)))
for line in lineList:
sorted_line = sorted(re.findall(r'\d+',line), key=lambda x:int(x))
After I read from file:
with open(fileName) as f:
for line in f:
print(line.split(",")) #split the file into multiple lists
How do I get some specific element(s) from those lists?
For example, only elements with index[0 to 3], but discard/ignore any elements after that.
If you want to save the first three items in each line, you could use a list comprehension
with open(fileName) as f:
firstitems = [line.rstrip().split(",")[0:3] for line in f]
Note that the rstrip() is needed to remove the final newline character, if there are fewer than four items in a line. Note that the "items" are all strings, even if they look like other types. If you want integers, for example, you will need to convert them to integers.
Then you can print them:
for line in firstitems:
print(line)
Try the below code:
with open('f.txt') as f:
print('\n'.join([i for i in f.read().split(',')[0:3]]))
I have a CSV file that contains matrix:
1,9,5,78
4.9,0,24,7
6,2,3,8
10,21.4,8,7
I want to create a function that returns list of lists:
[[1.0,9.0,5.0,78.0],[4.9,0.0,24.0,7.0],[6.0,2.0,3.0,8.0],[10.0,21.4,8.0,7.0]]
this is my attempt:
fileaname=".csv"
def get_csv_matrix(fileaname):
mat=open(fileaname,'r')
mat_list=[]
for line in mat:
line=line.strip()
mat_line=[line]
mat_list.append(mat_line)
return mat_list
but I get list of lists with one string:
[['1,9,5,78'], ['4.9,0,24,7'], ['6,2,3,8'], ['10,21.4,8,7']]
how can i turn the lists of strings to lists of floats?
mat_line = [line]
This line just takes the line as a single string and makes it into a one element list. If you want to separate it by commas, instead do:
mat_line = line.split(',')
If you want to also turn them into numbers, you'll have to do:
mat_line = [float(i) for i in line.split(',')]
I find it easier to read a list comprehension than a for loop.
def get_csv_matrix(filename):
with open(filename) as input_file:
return [[float(i) for i in line.split(',')] for line in input_file]
print (get_csv_matrix("data.csv"))
The above function opens a file (I use with to avoid leaking open file descriptors), iterates over the lines, splits each line, and converts each item into a floating-point number.
Try
fileaname=".csv"
def get_csv_matrix(fileaname):
mat=open(fileaname,'r')
mat_list=[]
for line in mat:
line=line.strip()
mat_line=line.split(",")
for i in mat_line:
i_position = line.index(i)
line[i_position] = float(i)
mat_list.append(mat_line)
return mat_list
If any object in mat_line isn't an integer, you will come up with an error, so I suggest you create a validation method to be absolutely sure that it is an integer.
I have a one line txt file, file1.txt, that has a series of 10 numbers as such;
10,45,69,85,21,32,11,71,20,30
I want to take these numbers from the txt file and then add them to a list and then sort the numbers in ascending order.
I have tried
myfile1 = open('file1.txt', 'r').readlines()
but this seems to give me a list of length 1, which obviously can't be sorted.
In [101]: myfile1
Out[101]: ['10,45,69,85,21,32,11,71,20,30']
I'm guessing there is something wrong with how I am reading the text file however I can't seem to find a suitable way.
.readlines() does what it says: it reads the file in line by line. In your example, there is only one line, so the length is 1.
With that one line, you need to split on commas:
with open(file1.txt,'r') as myfile:
for line in myfile:
print sorted(map(int, line.split(',')))
Or, if you have multiple lines with lots of numbers:
data = []
with open(file1.txt,'r') as myfile:
for line in myfile:
data.extend(map(int, line.split(',')))
print sorted(data)
Here I use with with keyword to open the file, which can be iterated over line by line. Then, use the the split method of strings on each line, which returns a list of strings. Then, I use map to convert these strings into integers by applying the int type casting function to each item in the list. This list can then be sorted. Make sure to take a look at the string methods page on the Python documentation.
A test without the input file:
numbers = "10,45,69,85,21,7,32,11,71,20,30"
data = []
data.extend(map(int, numbers.split(',')))
print sorted(data)
prints
[7, 10, 11, 20, 21, 30, 32, 45, 69, 71, 85]
A little obfuscated to do as a 1-liner, but basically:
with open('file1.txt', 'r') as f:
data = sorted(map(int, f.readline().split(',')))
What this does:
Read 1 line: f.readline()
Split that line on ',' characters: .split(',')
Map the list of string to int values: map(int, list)
Sort the list of int: sorted(list)