473,387 Members | 1,464 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

How can I combine a directory of .txt files into one AND insert their filenames

3
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
Apr 4 '08 #1
6 1790
micmast
144 100+
afaik you could do something like this:

Expand|Select|Wrap|Line Numbers
  1. master = open(masterfile,'a') # or write, whatever you need
  2. smallfile = open(smallerfile,'r')
  3.  
  4. for line in smallfile.readlines():
  5.        master.write(smallfilename+"\t"+line)
  6.  
Then repeat that for every smaller file
Apr 4 '08 #2
jlm699
314 100+
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.
Expand|Select|Wrap|Line Numbers
  1. >>> import os
  2. >>> os.getcwd()  ## This will return the current working directory
  3. 'C:\\Python24\\Lib\\site-packages\\wx-2.8-msw-unicode\\wx\\py'
  4. >>> os.path.join('foo', 'somedir', 'bar')  ## This is convenient so you don't have to worry about using / on *nix and \\ on windows
  5. 'foo\\somedir\\bar'
  6. >>> os.chdir(os.path.join('C:\\', 'Documents and Settings', 'Administrator', 'Desktop', 'pythtests'))  ## Changes the current working directory
  7. >>> os.getcwd()
  8. 'C:\\Documents and Settings\\Administrator\\Desktop\\pythtests'
  9. >>> os.listdir('.')  ## Returns list of names of files and dirs in cwd
  10. ['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']
  11. >>> 
  12. >>> ## So let's do something like this.......
  13. >>> mydirectory = os.path.join('C:\\', 'Documents and Settings', 'Administrator', 'Desktop', 'pythtests')  ## You can set this to your desired path
  14. >>>
  15. >>> myfiles = os.listdir(mydirectory)
  16. >>> for file in myfiles:  ## We'll iterate through each file in the list
  17. ...     if os.path.isfile(os.path.join(mydirectory, file)):  ## Check it is a file and not a directory
  18. ...         fh = open(os.path.join(mydirectory, file), 'r')
  19. ...         ## Do your stuff here
  20.  
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
Apr 4 '08 #3
PDSTAR
3
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!
Apr 4 '08 #4
PDSTAR
3
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!
Apr 4 '08 #5
jlm699
314 100+
What's wrong with what you've tried? What are the errors that you are getting?
Apr 6 '08 #6
ghostdog74
511 Expert 256MB
Expand|Select|Wrap|Line Numbers
  1. import glob
  2. for filename in glob.glob("*.txt"):
  3.     for lines in open(filename):
  4.         print filename,lines.strip()
  5.  
on the command line
Expand|Select|Wrap|Line Numbers
  1. c:\test> python script.py > outfile.txt
  2.  
Apr 7 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

3
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!
5
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...
1
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,...
1
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...
6
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...
9
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...
1
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 ,...
2
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...
13
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...
0
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,...
0
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$) { } ...
0
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...
0
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
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...
0
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,...
0
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...

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.