Python String Formatting, need to continuously add to a string - python

I just started python, any suggestions would be greatly appreciated. I'm reading a table generated by another program and pulling out 2 numbers from each line, I'll call them a and b. (they are saved as flux and observed in my program) I need to take these two numbers from each line and format them like this-
(a,b),(a,b),(a,b) ect.
Each consecutive parenthesis is from the consecutive line, first a,b is from line 1, second a,b is from line 2, etc. I need to read the entire table however, the table length will vary.
This is what I have so far. It can read the table and pull out the numbers I need, however, I don't know how to put the numbers into the proper format. I want to say something recursive would be most efficient but I'm unsure of how to do that. Thank you in advance.
#!/usr/bin/python
file = open("test_m.rdb")
while 1:
line = file.readline()
i = line.split()
flux = i[2]
observed = i[4]
if not line:
break

with open("test_m.rdb") as inf:
results = [(i[2],i[4]) for i in (line.split() for line in inf)]
result_string = ",".join(str(res) for res in results)
or a more general formatter:
result_string = ", ".join("('{2}', '{4}')".format(*res) for res in results)

Very simple solution:
with open('data') as data:
print ', '.join('(%s, %s)' % (x.split()[2], x.split()[4])
for x in data.readlines())
Just use readlines to iterate over the lines in the file.

assuming that two values you got are str1 and str2
//inside a loop which iterates through your values
strTable = strTable + ['('+str1+')','('+str2+')']
hope oit will work, if it dont, comment , i will solve it.

Related

Reading a numerical data file and assigning to each items at the same time

I am a beginner in python, and I have a problem when I want to read my numeric data file that contains more lines. My data in the input file contains rows that include a counter number, three float numbers, and finally, a character letter that all of them separated by space.it look like this:
1 12344567.143 12345678.154 1234.123 w
2 23456789.231 23413456.342 4321.321 f
I want to assign each item in the line to a specific parameter that I can use them to other steps.
like this "NO"=first item "X"=second item "Y"=third item "code"=forth item
I am trying to write it as follow:
f1=open('t1.txt','r')
line: float
for line in f1:
print(line.split(', ',4))
f1=float
select(line.split('')
nob: object(1)=int(line[1, 1])
cnt = 0
print(nob)
cnt +=1
but received more error each time when I run the program. Anyone can help me?
The error is probably due to the wrong indentation: in Python indentation is part of the syntax. It would be helpful if you also included the error message in your question.
How about this:
all_first_numbers = []
with open('t1.txt', 'r') as f:
for line in f:
values = line.split()
first_number = int(values[0])
second_number = float(values[1])
letter_code = values[4]
# If you want to save all the first numbers in one array:
all_first_numbers.append(first_number)

Printing elements and ignoring last two element in a table

I have a text file containing:
SKT:SSG:2:1
LN:FNC:1:1
NWS:ENY:2:0
I want to print out the elements in a table ignoring the last two elements which are the digits. Here's what I've done so far:
fileName = input("Enter file name:")
match = open(fileName)
table = []
for line in match:
contents = line.strip().split(':')
table.append(contents)
#add a loop to leave out last two digits?
print(table)
The output I get for a start is:
[['SKT','SSG','2','1'],['LN','FNC','1',1'],['NWS','ENY','2','0']]
The output I want:
[['SKT','SSG'],['LN','FNC'],['NWS','ENY']]
I've looked into a term known as array slicing and managed to come up with:
for i in range(len(table)):
print(table[i][:-2])
but I do not know how to implement it into the code I've written as I'm not familiar with file reading just yet. Any help is appreciated. Regards.
Assuming the full row is needed in table for another usage, you can create a new list and print the new one:
print([row[:-2] for row in table])
If the full row is not required, you can add just the relevant values, as CoryKramer mentioned in the question comments.
You can simply modify your current code as below:
contents = line.strip().split(':')[:-2]
Keep the remaining code as it is. Split method returns a list, so you can do slicing on it as well.
This code reads the file line by line. Each line is split on the ':' character to form a list and the list is appended to the table list to form a list of lists. Finally the each list in table is printed minus its last two elements.
fileName = input("Enter file name:")
match = open(fileName)
table = []
for line in match:
contents = line.strip().split(':')
table.append(contents)
print([content[:-2] for content in table])

List Index Out Of Range error when not out of range

I have a data file which only contains the following line:
"testA" "testB":1:"testC":2
Now when I split this line, and print the resulting list(w) I get the following:
['"testA"', '"testB":1:"testC":2']
[]
Now when I want to access w[0], it returns "testA" just fine, but when I print w[1], it crashes and gives a list index out of range error, but still prints it out "testB":1:"testC":2
Any help would be much appreciated!
Your code does not crash on w[1] on the "testA" "testB":1:"testC":2 line, otherwise it would not print "testB":1:"testC":2. Note the additional [] in your output? Your file contains some more empty lines, which are split to [], and which will then produce that error even on w[0].
To fix the problem, you should check whether the line and/or the list created from that line is non-empty. (When testing the line, make sure to strip away any whitespace, such as the trailing newline character.) Your code should then look somewhat like this:
with open("test.txt") as f:
for line in f:
if line.strip(): # strip the `\n` before checking whether line is empty
w = line.split()
print(w[0], w[1])
working for me without any error:
>>> a = '"testA" "testB":1:"testC":2'
>>> b = a.split(' ')
>>> b
['"testA"', '"testB":1:"testC":2']
>>> b[0]
'"testA"'
>>> b[1]
'"testB":1:"testC":2'
ae you doing anything different?
I also cannot reproduce your error but want to share a tip that I use in situations where I'm reading from a file and splitting on a delimiter.
cleaned_list = [ a.strip() for a in input_line.split(' ') if a ]
Simple and sanitizes the split list well.
The answer was that the program read the next line after the first one which it split, and that line was empty. So as soon as it tried to index the content of that (empty line) it crashed. That's why it DID print the first line, and then crashed. Thanks a lot for your help, though!

Trying to read a file and loop through at the same time

I'm pretty new to this so please move this topic if it's in the wrong place or something else.
Problem: (Quick note: This is all in Python) I am trying to go through these 100 or so files, each with the same number of columns, and take certain columns of the input (the same ones for each file) and write them in a new file. However, these 100 files don't necessarily all have the same number of rows. In the code below, filec is in a loop and continues altering throughout the 100 files. I am trying to get these certain columns that I want by looking at the number of rows in each txt file and looping that many times then taking the numbers I want.
filec = open(string,'r').read().split(',')
x = len(filec.readlines())
I realize the issue is that filec has become a list after using the split function and was originally a string when I used .read(). How would one go about finding the number of lines, so I can loop through the number of rows and get the positions in each row that I want?
Thank you!
You could do it like this:
filec = open (filename, 'r')
lines = filec.readlines ()
for line in lines:
words = line.split(',')
# Your code here
Excuse me if there are any errors, I'm doing this on mobile.
As you are just looking for the count of rows, then how about this -
t = tuple(open(filepath\filename.txt, 'r'))
print len(t)
I tried to keep the code clear, it is very possible to do with fewer lines. take in a list of file names, give out a dictionary, mapping the filename to the column you wanted (as a list).
def read_col_from_files(file_names, column_number):
ret = {}
for file_name in file_names:
with open(file_name) as fp:
column_for_file = []
for line in fp:
columns = line.split('\t')
column_for_file.append(columns[column_number])
ret[file_name] = column_for_file
return ret
I have assumed you have tab delimited columns. Call it like this:
data = read_col_from_files(["file_1.txt", "/tmp/file_t.txt"], 5)
Here is a sensible shortening of the code using a list comprehension
def read_col_from_files(file_names, column_number):
ret = {}
for file_name in file_names:
with open(file_name) as fp:
ret[file_name] = [line.split('\t')[column_number] for line in fp]
return ret
And here is how to do it on the command line:
cat FILENAMES | awk '{print $3}'

Python: writing a data file with three columns of integers

The code I am working with is:
fout = open('expenses.0.col', 'w')
for line in lines:
words = line.split()
amount = amountPaid(words)
num = nameMonth(words)
day = numberDay(words)
line1 = amount, num, day
fout.write(line1)
fout.close()
There is a file that you cannot see that the line in lines is pulling from which runs just fine. There are 100 lines within lines. When writing this last bit of code the goal is to get 100 lines of three columns which consist of the values: amount, num, and day. All three of these values are integers.
I have seen similar questions asked such as [python]Writing a data file using numbers 1-10, and I get the same error as that example. My problem is applying dataFile.write("%s\n" % line) to my case with three numbers in each line. Should be a quick 1 line of code fix.
In your example, line1 is a tuple - of numbers (I assume the functions amountPaid(), nameMonth(), numberDay() all return an integer or float).
You could do one of two things:
have these functions return the numbers as strings values
or cast the return values as string i.e.: amount =
str(amountPaid(words))
Once these values are strings you can simply do:
line1 = amount, num, day, '\n'
fout.write(''.join(line1))
Hope that helps!
use the print statement/function rather than the write method.
line1 = amount, num, day
fout.write("{}\n".format("".join(str(x) for x in line1)))

Categories

Resources