Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pass a python variable to subprocess 1

Status
Not open for further replies.

huangwason

Programmer
Oct 10, 2006
21
DE
I am thinking about a python script to generate a xml file from a csv file, every row in csv is an element for the generated xml file. In order to obtain file value in csv file, I used awk. In example

for i in range(int(total_line)):
elementName=os.popen("awk -F ':' 'NR==a {print $5}' a=i input.csv").read()

I'd like to fetch the ith row and 5th column value and assign it to python variable. The problem is I need to pass the python variable "i" to awk to select a line. How to solve this problem? Thanks in advance.
 
Hi

Only to answer your question :
Code:
[b]for[/b] i [b]in[/b] [COLOR=darkgoldenrod]range[/color][teal]([/teal][COLOR=darkgoldenrod]int[/color][teal]([/teal]total_line[teal])):[/teal]
     elementName[teal]=[/teal]os[teal].[/teal][COLOR=darkgoldenrod]popen[/color][teal]([/teal][green][i]"awk -F ':' 'NR==a {print $5}' a=%d input.csv"[/i][/green] [teal]%[/teal] i[teal]).[/teal][COLOR=darkgoldenrod]read[/color][teal]()[/teal]
But please give up with that stupidity. If you want to use Python, then use Python :
Code:
[red]import[/red] fileinput

[b]print[/b] [green][i]'<root>'[/i][/green]
[b]for[/b] line [b]in[/b] fileinput[teal].[/teal][COLOR=darkgoldenrod]input[/color][teal]():[/teal]
  [b]print[/b] [green][i]'  <row>'[/i][/green]
  [b]for[/b] field [b]in[/b] line[teal].[/teal][COLOR=darkgoldenrod]rstrip[/color][teal]().[/teal][COLOR=darkgoldenrod]split[/color][teal]():[/teal]
    [b]print[/b] [green][i]'    <field>%s</field>'[/i][/green] [teal]%[/teal] field
  [b]print[/b] [green][i]'  </row>'[/i][/green]
[b]print[/b] [green][i]'</root>'[/i][/green]
Code:
one two three
four five six
seven eigth nine
Code:
[b]<root>[/b]
  [b]<row>[/b]
    [b]<field>[/b]one[b]</field>[/b]
    [b]<field>[/b]two[b]</field>[/b]
    [b]<field>[/b]three[b]</field>[/b]
  [b]</row>[/b]
  [b]<row>[/b]
    [b]<field>[/b]four[b]</field>[/b]
    [b]<field>[/b]five[b]</field>[/b]
    [b]<field>[/b]six[b]</field>[/b]
  [b]</row>[/b]
  [b]<row>[/b]
    [b]<field>[/b]seven[b]</field>[/b]
    [b]<field>[/b]eigth[b]</field>[/b]
    [b]<field>[/b]nine[b]</field>[/b]
  [b]</row>[/b]
[b]</root>[/b]

Feherke.
 
IMHO, instead of reading CSV file with awk and writing XML file with python, you can do both things with python.
In one python program you can read CSV file, parse values from it and write them into XML file.
 
Thank you very much, I will consider that use a complete python script for the object.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top