Python write a list to a text file - string

I am using python format method to write a list of numbers into a text file. When the list length is fixed I can do:
a = [16,1,16,1]
myfile.write('{0},{1},{2},{3}'.format(*a) + "\n")
My question is how to use the format method when the size of list is not fixed. Is there any easy easy way of doing this? Rather than first create a string b, and then map a to b. I am not sure if I can use something like myfile.write('{all elements in a}'.format(*a) + "\n")
b=''
for i in range(len(a)):
if i<(len(a)-1):
b=b+'{'+ str(i) + '},'
else:
b=b+'{'+ str(i) + '}'
myfile.write(b.format(*a) + "\n")

Use str.join:
>>> lis = [16,1,16,1]
>>> ','.join(str(x) for x in lis) + '\n'
'16,1,16,1\n'
>>> lis = range(10)
>>> ','.join(str(x) for x in lis) + '\n'
'0,1,2,3,4,5,6,7,8,9\n'

Related

Can't run while loop through csv files using python

I'm having some trouble looping through the code below., Essentially, I am attempting to loop through a folder of files ("filename_x.csv") and remove all commas out within the fields, then I would like for the output to be saved with the "out". The code works like a charm if I input the counter individually, but it will not move to the next count. I know this is very close to functional status, but the 'with' statements may allow the other files to close, so it can't move to the next count or iteration (file path is just an example). Please, help!
import pandas as pd
n = 1
x = str(n)
while n < 9:
import csv
with open("C:\\Desktop\\server_"+x+".csv",'r', newline='') as infile, open("C:\\Desktop\\server_"+x+"_out.csv",'w', newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for row in reader:
writer.writerow(item.replace(",", "") for item in row)
n += 1
The line:
x = str(n)
is in the wrong place it needs to be in the loop at the top.
You only set at to the initial value of n and then it stays that way.
You do not actually even need it. Just put the str(n) directly in the string creation like this:
"C:\\Desktop\\server_" + str(n) + ".csv"
I would also recommend you use a different loop structure. The while format you are using does not make sense for the way you are using it. You should be using a for loop, like this:
import pandas as pd
import csv
for n in range(1, 9):
with open("C:\\Desktop\\server_" + str(n) + ".csv",'r', newline='') as infile, open("C:\\Desktop\\server_" + str(n) + "_out.csv",'w', newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for row in reader:
writer.writerow(item.replace(",", "") for item in row)
This fixes a few things. You simplify the code, but also there were some other issues. You had the increment of n in the wrong place which this corrects. Also you were doing the import cvs inside the loop which would probably not break anything, but would at the very least be inefficient since it would attempt reload the cvs module every pass through the outer loop.
Asssuming you have files server_1.csv, server_2.csv ...
Two things:
you don't need to keep track of both x and n
you need to increment n in the right place. You are currently incrementing it once per row.
import pandas as pd
import csv # <<< no need to repeat the import statement though it's harmless
n = 1
while n < 9:
with open("C:\\Desktop\\server_" + str(n) + ".csv",'r', newline='') as infile, open("C:\\Desktop\\server_" + str(n) + "_out.csv",'w', newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for row in reader:
writer.writerow(item.replace(",", "") for item in row)
# finished with this file, increment n
n += 1

Python Parameterize Formatting

So I was wondering if there was a way to parameterize the format operator
For example
>>> '{:.4f}'.format(round(1.23456789, 4))
'1.2346
However, is there anyway to do something like this instead
>>> x = 4
>>> '{:.xf}'.format(round(1.23456789, x))
'1.2346
Yes, this is possible with a little bit of string concatenation. Check out the code below:
>>> x = 4
>>> string = '{:.' + str(x) + 'f}' # concatenate the string value of x
>>> string # you can see that string is the same as '{:.4f}'
'{:.4f}'
>>> string.format(round(1.23456789, x)) # the final result
'1.2346'
>>>
or if you wish to do this without the extra string variable:
>>> ('{:.' + str(x) + 'f}').format(round(1.23456789, x)) # wrap the concatenated string in parenthesis
'1.2346'

outputting a list of tuples to a new file in a certain format

let's say I have a list of tuples my_list=[(who,2), (what,5), (where, 1)]
I want to write in into a new file (new_file.txt) in this format:
who,2
what,5
where, 1
One above the other, with no brackets and only inner commas.
This does not work:
with open('new_file.txt', 'w') as fd:
a = '\n'.join(str(x) for x in results)
fd.write('\n'.join(a))
fd.close()
Will appreciate your help !
results = [('who', 2), ('what', 5), ('where', 1)]
def line(u):
return ','.join(map(str, u))
with open('new_file.txt', 'w') as fd:
fd.write('\n'.join([line(u) for u in results]))
One note: you don't have to close the file explicitly, because with closes it for you.
If the results list is very long, you may not want to construct the file content in one go, but write them line by line:
with open('new_file.txt', 'w') as fd:
for u in results:
fd.write(line(u) + '\n')
You have converted the tuple to a string hence this might not work. A quick solution could be something like this assuming this is input data you are expecting:
results = [("who",2), ("what",5), ("where", 1)]
with open('new_file.txt', 'w') as fd:
data_str = ""
for data in results:
data_str += str(data[0]) + ',' + str(data[1]) + '\n'
fd.write(data_str)

copy variable name with some order in python

like to copy some variable with some calculation.
There is a list and I want to make multiple lists by copy the list.
fruit=['apple','orange']
below lists I want to create from original list
fruit1=['apple1','orange1']
fruit2=['apple2','orange2']
fruit3=['apple3','orange3']
please help
You can try this:
import inspect
fruit = ['apple', 'orange']
def get(v):
for i in reversed(inspect.stack()):
n = [v_name for v_name, v_val in i.frame.f_locals.items() if v_val is v]
if len(n):
return n[0]
for i in range(1, 4):
name_string_order = get(fruit) + str(i)
exec("%s = [fruit[0] + str(i), fruit[1] + str(i)]" % name_string_order)
print(fruit1)
print(fruit2)
print(fruit3)
And out put
['apple1', 'orange1']
['apple2', 'orange2']
['apple3', 'orange3']

How to change behaviour of str(aList) in python

I'm trying to extract information from a very large XML file by parsing it with a python(v2.7.10) script. The goal is to make this information available to my other project written in C as (very large) array and integer literals in a file.
The following code demonstrates what I'm doing:
import sys
myList = [[1,2,3],[11,22,33]]
size = len(myList)
print("int myList[" + str(size) + "][3] = " + str(myList) + ";\n")
The result of this is int myList[2][3] = [[1,2,3],[11,22,33]];, but what I need is C syntax: int myList[2][3] = {{1,2,3},{11,22,33}};
Is there a way to modify str() in a way that it uses {} instead of [] for printing lists?
You can use a translate table trans for that, and then use the str.translate(..) function:
from string import maketrans
trans = maketrans('[]','{}')
print("int myList[" + str(size) + "][3] = " + str(myList).translate(trans) + ";\n")
This then prints:
>>> from string import maketrans
>>> myList = [[1,2,3],[11,22,33]]
>>> size = len(myList)
>>> trans = maketrans('[]','{}')
>>> print("int myList[" + str(size) + "][3] = " + str(myList).translate(trans) + ";\n")
int myList[2][3] = {{1, 2, 3}, {11, 22, 33}};
But note that if the elements are not lists, this can result in content that is not semantically valid. We simply replace '[' by '{', and ']' by '}'.

Resources