Hello,
Any help would be much appreciated. I have a directory of ~2000 tab delimited .txt files. I would like to combine all these files (append to the last blank row) into a master file. The one catch is, I need the filename from which the data is drawn to be the first item in every row of the master file. For example:
I don't know how to insert tabs into this message, so I'll insert "|" where a tab would be.
File 1:
Name = "ABC.txt"
Row 1=dog|cat|mouse|
Row 2=mouse|cat|dog
File 2:
Name = "DEF.txt"
Row 1=frog|bug|grass
Row 2=grass|bug|frog
Ideally, I'd like the output (master file) to look like:
Row 1=ABC.txt|dog|cat|mouse|
Row 2=ABC.txt|mouse|cat|dog
Row 3=DEF.txt|frog|bug|grass
Row 4=DEF.txt|grass|bug|frog
The names of the 2000 text files will change from time to time, so I would like to be able to reference a directory in the code as opposed to each individual file.
I hope this is enough info. Thanks in advance for any help!
PD
6 1790
afaik you could do something like this: -
master = open(masterfile,'a') # or write, whatever you need
-
smallfile = open(smallerfile,'r')
-
-
for line in smallfile.readlines():
-
master.write(smallfilename+"\t"+line)
-
Then repeat that for every smaller file
Using the os.path module will give you a lot of flexibility when it comes to directories and file paths, including cross-platform functionality if that's what you fancy. -
>>> import os
-
>>> os.getcwd() ## This will return the current working directory
-
'C:\\Python24\\Lib\\site-packages\\wx-2.8-msw-unicode\\wx\\py'
-
>>> os.path.join('foo', 'somedir', 'bar') ## This is convenient so you don't have to worry about using / on *nix and \\ on windows
-
'foo\\somedir\\bar'
-
>>> os.chdir(os.path.join('C:\\', 'Documents and Settings', 'Administrator', 'Desktop', 'pythtests')) ## Changes the current working directory
-
>>> os.getcwd()
-
'C:\\Documents and Settings\\Administrator\\Desktop\\pythtests'
-
>>> os.listdir('.') ## Returns list of names of files and dirs in cwd
-
['bckmch.py', 'cmdtest.py', 'cobyla.py', 'elseerr.py', 'fileio.py', 'functest.py', 'graphics', 'hscore.py', 'ldict.py', 'lid', 'mainbody', 'matrixprint.py', 'matrx_print.py', 'module1.py', 'module1.pyc', 'module2.py', 'poopies.txt', 'Question', 'test.py', 'test2.py', 'tkinttxtbx.py', 'tktst.py', 'topload', 'totalbottle', 'trivgame.py', 'walkncount.py', 'wxtemplate.py']
-
>>>
-
>>> ## So let's do something like this.......
-
>>> mydirectory = os.path.join('C:\\', 'Documents and Settings', 'Administrator', 'Desktop', 'pythtests') ## You can set this to your desired path
-
>>>
-
>>> myfiles = os.listdir(mydirectory)
-
>>> for file in myfiles: ## We'll iterate through each file in the list
-
... if os.path.isfile(os.path.join(mydirectory, file)): ## Check it is a file and not a directory
-
... fh = open(os.path.join(mydirectory, file), 'r')
-
... ## Do your stuff here
-
Another level of security you could write into the for loop would be to take the file name (represented by string in file) and do file.split('.')[-1] == 'txt' . This will ensure you've got a .txt file and not something else hidden in your directory.
Hope that helps.
P.S. like micmast said tab is represented by the escape character \t
Thanks a ton! This will hopefully make my life a lot easier. So if I understand correctly, I will tack on micmast's code to the bottom of jlm699's code and modify where necessary. I will try this out ASAP.
Thanks again!
Hi again,
I'm sorry- I don't want to ask anyone to have to hold my hand through the whole thing, but I've tried the suggested code, and I can't get it to work. I must be doing something wrong.
If all the text files I'm combining are in the directory "C:\Documents and Settings\pd\Desktop\Pythontest", what exactly should the full code look like?
Thanks so much again!
What's wrong with what you've tried? What are the errors that you are getting?
-
import glob
-
for filename in glob.glob("*.txt"):
-
for lines in open(filename):
-
print filename,lines.strip()
-
on the command line -
c:\test> python script.py > outfile.txt
-
Sign in to post your reply or Sign up for a free account.
Similar topics
by: NotGiven |
last post by:
I am researching the best place to put pictures. I have heard form both
sides and I'd like to know why one is better than the other.
Many thanks!
|
by: Raj |
last post by:
Hi all,
Can anyone help me with a script which would delete files or
move them to a different folder at some scheduled time..!
Please.....!!!
Thanks in advance...
|
by: tom lewton |
last post by:
if the following article is to be believed:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/supported_file_systems.asp
a directory can contain 66534 files. however,...
|
by: JS |
last post by:
Does anybody know how I can get the just the selected directory from an
OpenFileDialogBox?
I have tried GetDirectoryName and GetFullPath, but these two require that I
manually input in the code...
|
by: bindslind |
last post by:
Hello. Pretty new to PHP(and any sort of programming), I've been trying to modify this script that was originally written to display mysql data so it will paginate images from a directory. The code...
|
by: Wolfgang Draxinger |
last post by:
H folks,
I got, hmm not really a problem, more a question of elegance:
In a current project I have to read in some files in a given
directory in chronological order, so that I can concatenate...
|
by: jo3c |
last post by:
hi everybody
im a newbie in python, i have a question
how do u parse a bunch of text files in a directory?
directory: /dir
files: H20080101.txt ,...
|
by: nothing1 |
last post by:
Here is my code and what it does is create a page for every directory with the contents of choice.
Its been working on all letters except "u" I can't seem to figure it out.
Does someone see the...
|
by: lawpoop |
last post by:
Hello all -
I have a two part question.
First of all, I have a website under /home/user/www/. The index.php
and all the other website pages are under /home/user/www/. For
functions that are...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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,...
|
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...
| |