473,729 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding a column in a tab delimited txt file

Hi, I am new to python, hope someone can help me here:
I have a MS Access exported .txt file which is tab delimited in total
20 columns, now I need to add another column of zero at the 4th column
position and a column of zero at the 9th column position. What is the
best way to do this? Can I write a while loop to count the number of
tab I hit until the counter is 4 and then add a zero in between and
thru the whole file?

Thanks,
Garry
Jul 18 '05 #1
4 19310
Garry wrote:
Can I write a while loop to count the number of
tab I hit until the counter is 4 and then add a zero in between and
thru the whole file?


Try using the split string method and then the insert list method.

Untested code:

###
infile = file("in.txt")
outfile = file("out.txt")

for line in f:
columns = line.split("\t" )
columns.insert( 4, "0")
outfile.write(" \t".join(column s)+"\n")
###

The code might not be perfect, but you get the idea.

--------------------------------------------------
Blake T. Garretson http://blakeg.freeshell.org

Jul 18 '05 #2
Blake Garretson wrote:
for line in f:


I meant "for line in infile:"

Sorry!

--------------------------------------------------
Blake T. Garretson http://blakeg.freeshell.org

Jul 18 '05 #3
>>>>> "Garry" == Garry <gc***@hotmail. com> writes:

Garry> Hi, I am new to python, hope someone can help me here: I
Garry> have a MS Access exported .txt file which is tab delimited
Garry> in total 20 columns, now I need to add another column of
Garry> zero at the 4th column position and a column of zero at the
Garry> 9th column position. What is the best way to do this? Can I
Garry> write a while loop to count the number of tab I hit until
Garry> the counter is 4 and then add a zero in between and thru
Garry> the whole file?

Unless the file is terribly large, it will be easier to slurp the
whole thing into memory, manipulate some list structures, and then
dump back to the file.

There are a couple of nifty things to speed you along. You can use
string split methods to split the file on tabs and read the file into
a list of rows, each row split on the tabs.

rows = [line.split('\t' ) for line in file('tabdelim. dat')]

The next fun trick is to use the zip(*rows) to tranpose this into a
list of columns. You can then use the list insert method to insert
your column. Here I'm adding a last name column to the third column.

cols = zip(*rows) # transposes 2Dlist
cols.insert(2, ['Hunter', 'Sierig', 'Hunter', 'Hunter'])

Now all that is left is to transpose back to rows and write the new
file using the string method join to rejoin the columns with tabs

rows = zip(*cols) # transpose back
file('newfile.d at', 'w').writelines (['\t'.join(row) for row in rows])

This script takes an input file like

1 John 35 M
2 Miriam 31 F
3 Rahel 5 F
4 Ava 2 F

and generates an outfile

1 John Hunter 35 M
2 Miriam Sierig 31 F
3 Rahel Hunter 5 F
4 Ava Hunter 2 F

Damn cool!

Here is the whole script:

rows = [line.split('\t' ) for line in file('tabdelim. dat')]
cols = zip(*rows)
cols.insert(2, ['Hunter', 'Sierig', 'Hunter', 'Hunter'])
rows = zip(*cols)
file('newfile.d at', 'w').writelines (['\t'.join(row) for row in rows])

Cheers,
John Hunter

Jul 18 '05 #4
-
gc***@hotmail.c om (Garry) wrote in message news:<b3******* *************** ****@posting.go ogle.com>...
Hi, I am new to python, hope someone can help me here:
I have a MS Access exported .txt file which is tab delimited in total
20 columns, now I need to add another column of zero at the 4th column
position and a column of zero at the 9th column position. What is the
best way to do this?


I don't know the best way, but one way is this.

import re

infile = file("in.txt"," r")
outfile = file("out.txt", "w")

pattern = re.compile(r'^( (?:[^\t]+\t){3})((?:[^\t]+\t){5})')
replace = '\g<1>0\t\g<2>0 \t'

for line in infile:
outfile.write(p attern.sub(repl ace,line))
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
4725
by: jrlen balane | last post by:
how would i read a tab delimited file? at the same time put what i read in an array, say for example that i know that the file is an array with column= 5 and row=unknown.
2
1746
by: DC Gringo | last post by:
I am outputting a datatable to a tab-delimited file. This all works well and good with 2 issues: 1) There is some data in my table that looks like this: <a_tag>theData</a_tag>. I would like to be able to strip out the tags before writing to the csv file 2) If there are 100 rows output, then the 102nd row has the HTML of the ..aspx webform that contains the button which calls the tab-delimitedf-ile-writing function. How can I get...
3
2790
by: monte | last post by:
Hello, I need to parse a tilde delimited file and output it to a tabbed delimited file. Example file example.txt data1~data2~data3~data4 data5~data6~data7~data8 I need to extract data2, data4, data6 and data8 from the above file and output it to a file delimited by tabs: data2 data4 data6 data8
3
5432
by: Elmo Watson | last post by:
I've been asked to develop a semi-automated type situation where we have a database table (sql server) and periodically, there will be a comma delimited file from which we need to import the data, replacing the old. I naurally know that we can use to kill the other data, but does anyone have any examples of importing a comma delimited file into SQL Server with ASP?
6
1791
by: Skc | last post by:
I am trying to import a file using a custom VB.net procedure, but the problem is it works on a file with pure comma separation and not inverted commas and commas, i.e. it works for AAA,BBB,CCC,DDD but not for "AAA","BBB","CCC","DDD". Here is an extract from the code which needs to be modified for the """: Sub LoadTextFile(ByVal strFilePath As String) Dim oDS As New DataSet() Dim strFields As String Dim oTable As New DataTable()
5
6501
by: Karl Irvin | last post by:
I'm using the Write # statement to create a csv export file from Access 2K Some of the data has embedded quotes in it and it doesn't import into QuickBooks correctly. An inventory part with a name of 1/4" Pipe gets truncated to 1/4 with csv Can I create a tab delimited file with Aceess and include the quote mark.
1
7815
jwwicks
by: jwwicks | last post by:
Hello All, This is a student assignment. So I don't want the complete answer just a hint or maybe a bumb on the head cause I'm doing it the wrong way. Assume I haven't done anything braindead like not include a header etc... I can post the whole code if you like/need it but I'm trying to spare the forum :) Got a product structure... struct product { string id; string description; int quantity;
0
1870
by: Kristi | last post by:
I need to create a CL program that will take a PF, and create a tab delimited file that has comma seperated column headings as the first record. I know i can use cpytostmf/cpytoimpf to create the file, but how do i get the headings to be comma seperated while the rest of the file is tab delimited? Any help would be wonderful. Thank you
11
1903
by: kimmelsd33 | last post by:
I would like some expert advice. I am writing in VB6. I am opening a tab delimited file, deleting the first 50 lines, and rewriting the file to a temp file. The temp file has about 20 columns with x number of lines. What I am trying to do, is open the tab delimited file, and read each column into a named variable, ex. depth<column1>mpf<column2>tg<column3>,etc. I have written a function to take the variable from column2(mpf) & create another...
7
3335
by: kimmelsd33 | last post by:
I am using VB6. I want to read a tab delimited file, and assign each column value into a variable. If the variable is "-999.25", I want to make it a "0". I then want to reassemble the values, and write them to a temp text file. Starting with line 64, I have about 28 columns and x number of rows. Ex: 1000<tab>23.3<tab>-999.25<tab> etc. The value of -999.25 can be in any column. I need to replace it before it is stored in the variable. I need to...
0
8763
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9427
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9284
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9202
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9148
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8151
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4796
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2165
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.