write the same data into many lines in text file python - python-2.7

I would like to write the same information for many lines into a text file. Basicly, I have a list of numbers. I want to write these number in one line and then copy the first line to the next 400 lines.
My code at the moment is
outfile = open(outfilename+'.dat','w')
for j in range (0,len(elevation_list)):
outfile.write(elevation_list[j]+' ')
outfile.close()
And it only writes the first line.
For example, my elevation list is 1, 2, 3, 4, 5
I want my text file like the following
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
Can anyone please help me with this?

Do you have any line breaks in your elevation list? Try this instead:
elevations = ""
for elevation in elevation_list:
elevations+= elevation
outfile = open(outfilename+'.dat','w')
for i in range(400):
outfile.write(elevations +'\n')
outfile.close()

This is what you want:
class RepeatedWrite(object):
def __init__(self, elevation_list, no_of_lines=5, outfilename="outfile.dat"):
self.elevation_list = elevation_list
self.no_of_lines = no_of_lines
self.outfilename = outfilename
def write_to_file(self):
with open(self.outfilename, 'w') as fp:
for i in xrange(self.no_of_lines):
fp.write(' '.join([str(ele) for ele in self.elevation_list]))
fp.write("\n")
elevation_list = [1, 2, 3, 4, 5]
RepeatedWrite(elevation_list).write_to_file()

Related

How can I print output with a defined number of characters in each line with python?

I used textwrap.fill (textwrap.fill(text, 6)) to limit each line in only 6 characters, but there is a problem with using this command because my purpose is go to new line exact at 6 character, I mean:
for example using textwrap.fill(I am a student, 8):
what I want:
(I am a s
tudent)
output:
(I am a
student)
One approach:
>>> text = 'I am a student, 8'
>>> text = 'I am a student'
>>> for i in range(0, len(text), 8):
... print text[i:i+8]
...
I am a s
tudent
for i in range(0, len(text), 8) means "Give me numbers starting at 0, incrementing by 8 at a time, and ending before the length of the text."
EDIT
If you want the value in a single string:
>>> wrapped = "\n".join(text[i:i+8] for i in range(0, len(text), 8))
>>> wrapped
'I am a s\ntudent'

Getting len(a) of a list a imported from a file in Python 2.7

This should work just fine. I cannot understand why I am getting this result, though. I have a programme, which opens a text file.
file2 = open('file.txt','r')
The text file contains 5 lines. To put them into a list, I do:
data2 = file2.readlines()
Then, I can make a variable containing the third line by doing so:
var = data2[2]
The third line of the text file contains a list, with numbers from 1-12, each one being a seperate string.
['1','2','3','4','5','6','7','8','9','10','11','12']
Finally, I print the length of the list,
print len(var)
Instead of getting 12, I get 53. I even tried that:
print len(data2[2])
Which apparently didn't work. Any explaination?
data2[2] is a string in the provided example. It has 53 characters in it. You will need to convert it to an array by some kind of string manipulation/parsing.
Something like:
>>> line = "['1','2','3','4','5','6','7','8','9','10','11','12'] "
>>> len(line)
53
>>> line = line.strip()
>>> line = line.replace('[','')
>>> line = line.replace(']','')
>>> line = line.replace("'","")
>>> line
'1,2,3,4,5,6,7,8,9,10,11,12'
>>> nums = [int(s) for s in line.split(',')]
>>> nums
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> len(nums)
12

create multiple lists for a given test data in python

I am relatively new to python so please excuse me if this is a very rudimentary question. This is my first time asking question.
I have a test file which is of the format below.
1 2 4
1 3 2
1 4 1
2 1 2
2 2 1
2 3 1
3 2 3
3 7 1
4 1 1
....
I am trying to read the file line by line and for each value in column 1 (1, 2, 3...), i need to create a list of the form below
list_1 = [[2,4], [3,2], [4,1]]
list_2 = [[1,2], [2,1], [3,1]]
list_3 = [[2,3], [7,1]]
list_4 = [[1,1]]
...
list_n
where values in the list are from column 2 and column 3 respectively.
Sincerely appreciate any guidance in this regard. Thank you
Use a defaultdict. This way, you don't have to check if your key already exists in the dictionary.
from collections import defaultdict
def parse(filename):
result = defaultdict(list)
with open(filename) as infile:
for line in infile:
c1, c2, c3 = map(int, line.split())
result[c1].append([c2, c3])
return result
def main():
result = parse("test_data.txt")
print(result)
if __name__ == '__main__':
main()

Python: Write two lists into two column text file

Say I have two lists:
a=[1,2,3]
b=[4,5,6]
I want to write them into a text file such that I obtain a two column text file:
1 4
2 5
3 6
Simply zip the list, and write them to a csv file with tab as the delimiter:
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> zip(a,b)
[(1, 4), (2, 5), (3, 6)]
>>> import csv
>>> with open('text.csv', 'w') as f:
... writer = csv.writer(f, delimiter='\t')
... writer.writerows(zip(a,b))
...
>>> quit()
$ cat text.csv
1 4
2 5
3 6
You can use numpy.savetxt(), which is a convenient tool from the numpy library.
A minimal example would be as follows:
import numpy as np
xarray = np.array([0, 1, 2, 3, 4, 5])
yarray = np.array([0, 10, 20, 30, 40, 50])
# here is your data, in two numpy arrays
data = np.column_stack([xarray, yarray])
datafile_path = "/your/data/output/directory/datafile.txt"
np.savetxt(datafile_path , data, fmt=['%d','%d'])
# here the ascii file is written.
The fmt field in np.savetxt() in the example specifies that the numbers are integers.
You can use a different format for each column.
E.g. to specify floating point format, with 2 decimal digits and 10 characters wide columns, you would use '%10.2f'.
Try this:
file = open("list.txt", "w")
for index in range(len(a)):
file.write(str(a[index]) + " " + str(b[index]) + "\n")
file.close()
A simple solution is to write columns of fixed-width text:
a=[1,2,3]
b=[4,5,6]
col_format = "{:<5}" * 2 + "\n" # 2 left-justfied columns with 5 character width
with open("foo.csv", 'w') as of:
for x in zip(a, b):
of.write(col_format.format(*x))
Then cat foo.csv produces:
1 4
2 5
3 6
The output is both human and machine readable, whereas tabs can generate messy looking output if the precision of the values varies along the column. It also avoids loading the separate csv and numpy libraries, but works with both lists and arrays.
You can write two lists into a text file that contains two columns.
a=[1,2,3]
b=[4,5,6]
c = [a, b]
with open("list1.txt", "w") as file:
for x in zip(*c):
file.write("{0}\t{1}\n".format(*x))
Output in the text file:
1 4
2 5
3 6
It exits a straightway to save and stack same vectors length in columns. To do so use the concatenate function, you can then stack 3,4 or N vectors in columns delimitered by a tab.
np.savetxt('experimental_data_%s_%.1fa_%dp.txt'%(signal,angle,p_range), np.c_[DCS_exp, p_exp], delimiter="\t")

read an integer list and return into a format python

If I open a file with the following in it:
1 2 3 4 \n
5 6 7 \n
8 9 10
so
def read(list):
list = open('list.tet','r')
nums = list.readlines()
new_list = []
for num in nums:
if num.find('\n'):
new_list.append(num.strip('\n')
return new_list
I hope to get the output as
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
What should I do?
Thank you
You can try the following to read out your integers if you have a fix seperator ( like the space ):
new_list = []
with open( "list.tet", "r" ) as myFile:
for myLine in myFile:
for myInt in myLine.strip().split( " " ):
new_list.append( myInt )
print( "Integers:", new_list )
It is not the perfect python way as you can compress those lines even more but I thought that it is a bit easier to understand. The good thing is that you have built in failure handling if the file 'list.tet' is missing.
The example will open your file and read one line after another as 'myLine'. Than it will strip any leading/trailing spaces/tabs/newline characters from this line leaving you with "1 2 3" for the first line. The split than separate those into [1, 2, 3] we use in the for loop to put each value into myInt that than got appended to your new_list.