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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help creating a CSV file

Status
Not open for further replies.

bigbalbossa

Programmer
Mar 21, 2002
87
US
What are my options for creating a CSV file using the two example flat files below? I understand how to loop through and read the files, but not sure how to put the data together.

File1:
"Count"="779022"
"Data Mart"="Sprint"
"Version"="73"
"Username"="stedem"
"Password"="stedem"
"Level Key"="PROFILE_ID"
File2:
"Count"="12345"
"Data Mart"="Dell"
"Version"="23"
"Username"="delmet"
"Password"="delmet"
"Level Key"="PROFILE_ID"

Output should look like:
779022, Sprint, 73, stedem, stedem, PROFILE_ID
12345, Dell, 23, delmet, delmet, PROFILE_ID
 
You have a LOT of options. How big are your files going to be? If you are just trying to lots of small files that contain a single record, as it were, I would probably just read in each file one at a time (pass the program a list of files to read). Then, for each line, do a split on '='. Take the second value and print it with a trailing ','. If it is the last record, print a newline instead of a comma.

As long as every file is in the same format, it should work. If not, you could read the files into a hash and print out from there.

As I said, tons of options. Which method is best really depends on how the system needs to work in the end.

 
The files will be small. Right now my code stores these files to an array and I loop through:

open(OUT, "$outfile") || die ...
foreach $file ( @ctrl ) {
open(INFILE, $file)
while(<INFILE>) {
chomp;
/\"(.+)\"=\"(.+)\"/;
if($1 eq "Count") {
my $count = $2;
print OUT "$count\n";
}
if($1 eq "Data Mart") {
my $dm = $2;
print OUT "$dm\n";
}
}
}

How do I print $count and $dm on the same line???

Thanks,
 
print OUT $count . " ";

#code

print OUT $dm . "\n";
 
Hmmm...I guess when you are struggling with something so simple, it's time to take a break.

Thanks for the help.
 
Another option would be to use the Text::CSV module. Unless you're positive there will be no commas or quotes in your data it's a good idea to use it.

ex:
"Count"="12345"
"Data Mart"="ACME, Inc."

In a CSV file, this would have to be written as:

12345,"ACME, Inc.", etc...

Otherwise, ACME and Inc would look like two separate fields in the csv file
The module does this all for you.. it wouldn't be too hard to code yourself, but why reinvent the wheel?
You could also just strip all commas and quotes before writing your output if you don't need them.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top