Hi,
I have just started using Python and I am slowly getting into it. I wanted to make a little script to merge all files in a directory into one.
All of these files will be text files.
I know I need to use os.path.walk() to walk through all the files, and if not os.path.isdir(f ilename) with open(filename,' r').read() to read all the files that are not directories.
Can someone give me a clue or a very simple example that I can work with please?
Thanks in advance.
6 30691 bvdet 2,851
Recognized Expert Moderator Specialist
Hi,
I have just started using Python and I am slowly getting into it. I wanted to make a little script to merge all files in a directory into one.
All of these files will be text files.
I know I need to use os.path.walk() to walk through all the files, and if not os.path.isdir(f ilename) with open(filename,' r').read() to read all the files that are not directories.
Can someone give me a clue or a very simple example that I can work with please?
Thanks in advance.
I think this code will do what you want: - import os
-
-
def dir_list(dir_name, subdir, *args):
-
'''Return a list of file names in directory 'dir_name'
-
If 'subdir' is True, recursively access subdirectories under 'dir_name'.
-
Additional arguments, if any, are file extensions to add to the list.
-
Example usage: fileList = dir_list(r'H:\TEMP', False, 'txt', 'py', 'dat', 'log', 'jpg')
-
'''
-
fileList = []
-
for file in os.listdir(dir_name):
-
dirfile = os.path.join(dir_name, file)
-
if os.path.isfile(dirfile):
-
if len(args) == 0:
-
fileList.append(dirfile)
-
else:
-
if os.path.splitext(dirfile)[1][1:] in args:
-
fileList.append(dirfile)
-
-
# recursively access file names in subdirectories
-
elif os.path.isdir(dirfile) and subdir:
-
# print "Accessing directory:", dirfile
-
fileList += dir_list(dirfile, subdir, *args)
-
return fileList
-
-
def combine_files(fileList, fn):
-
f = open(fn, 'w')
-
for file in fileList:
-
print 'Writing file %s' % file
-
f.write(open(file).read())
-
f.close()
-
-
if __name__ == '__main__':
-
search_dir = "C:/directory"
-
fn = "output_file.txt"
-
combine_files(dir_list(search_dir, False, 'txt'), fn)
Thanks , you have helped a lot :)
another way -
import os,shutil
-
f=open("/tmp/fileappend.txt","a")
-
for r,d,fi in os.walk("/home/me"):
-
for files in fi:
-
if files.endswith(".txt"):
-
g=open(os.path.join(r,files))
-
shutil.copyfileobj(g,f)
-
g.close()
-
f.close()
-
I think this code will do what you want: - import os
-
-
def dir_list(dir_name, subdir, *args):
-
'''Return a list of file names in directory 'dir_name'
-
If 'subdir' is True, recursively access subdirectories under 'dir_name'.
-
Additional arguments, if any, are file extensions to add to the list.
-
Example usage: fileList = dir_list(r'H:\TEMP', False, 'txt', 'py', 'dat', 'log', 'jpg')
-
'''
-
fileList = []
-
for file in os.listdir(dir_name):
-
dirfile = os.path.join(dir_name, file)
-
if os.path.isfile(dirfile):
-
if len(args) == 0:
-
fileList.append(dirfile)
-
else:
-
if os.path.splitext(dirfile)[1][1:] in args:
-
fileList.append(dirfile)
-
-
# recursively access file names in subdirectories
-
elif os.path.isdir(dirfile) and subdir:
-
# print "Accessing directory:", dirfile
-
fileList += dir_list(dirfile, subdir, *args)
-
return fileList
-
-
def combine_files(fileList, fn):
-
f = open(fn, 'w')
-
for file in fileList:
-
print 'Writing file %s' % file
-
f.write(open(file).read())
-
f.close()
-
-
if __name__ == '__main__':
-
search_dir = "C:/directory"
-
fn = "output_file.txt"
-
combine_files(dir_list(search_dir, False, 'txt'), fn)
This seemed to work for a while for me now it comes up with "NameError: name 'False' is not defined"
bvdet 2,851
Recognized Expert Moderator Specialist
This seemed to work for a while for me now it comes up with "NameError: name 'False' is not defined"
- >>> bool(0)
-
False
-
>>> bool(1)
-
True
-
>>>
'0' and '1' can be substituted for 'False' and 'True' respectively. The question is what happened to 'False' on your system?
- >>> bool(0)
-
False
-
>>> bool(1)
-
True
-
>>>
'0' and '1' can be substituted for 'False' and 'True' respectively. The question is what happened to 'False' on your system?
Did a quick reset on my machine and is working now. very strange.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Guillaume Lahitette |
last post by:
Hello everyone,
I am looking for a lightweight Java Applet to diff and merge two text
files. The functionality would be a subset of what WinMerge
(http://winmerge.sourceforge.net) offers:
- diff 2 text files
- merge (in both directions)
- color coding to highlight differences
I found some Java diff tools but they were all command line. And my
|
by: Charlie |
last post by:
Hello,
I have data in an Access table that I would like to export to multiple
HTML tables. I would like to split the data in the Access table
(about 92,000 records) into multiple HTML tables/files to reduce
download time and bandwidth usage on my web server. That way, the
user can select a particular page to download instead of downloading a
page with all of the records.
I would like to set a limit of only 500 records per file.
|
by: Chris Murphy via DotNetMonster.com |
last post by:
Hey all, just wondering if anyone can point me in the right direction. I'm
developing a solution that allows a user to store multiple text-based
content (like code snippets, notes, documents etc.) in one master document.
I'm not exactly sure which is the most efficient method of going about
this. Should I:
a. Use a container file like a CAB file and read/write separate textfiles
to it?
b. Save all "documents" in a collection and serialize...
|
by: Buddhist[CHinA] |
last post by:
The text files are not only the .txt files, but also all ascii files.
Thx.
|
by: malla |
last post by:
Hi,
I am trying to open a bunch of files and get data from them into one
single file. I am sure this process can be automated if I name the
files that I want to open in a regular pattern (say 1.txt, 2.txt,
3.txt, ...) Has anyone done sth like this before? Is there a way to
achieve this easily? Please share.
| |
by: ManningFan |
last post by:
I'm running through a database in a loop, and each time the loop
finishes I would like to export the values of some variables to new
text files. In reality it's more complex than this, but this is the
simplest way to state it.
Is there a way to write to text files and save them as different names
(presumably one of the variables dot "TXT") using Access VBA?
|
by: emaghero |
last post by:
Hello all, I want to open multiple txt files with similar names in C++
I have attempted this with the following code
//Create as many txt files as there are valid propagation constants
//Propagation constants are elements of the vector beta
for(int j=0;j<(int)(number_of_nodes);j++){
if(*(beta+j)>substrate*k && *(beta+i)<core*k){
FILE *p_j;
p_j=fopen("c:\\data_j.txt","w");
}
|
by: as001 |
last post by:
Hi,
I'm writing a windows application in C# using VS 2003.
I got stuck where it has to write multiple output text files. Here's my piece of code:
for loop
{
Random r = new Random();
//use millisecond and random to avoid similar filename
|
by: maral |
last post by:
Hi every one, this is my first post here!
I'm using GATE toolkit for information retrieval and text analysis, but i really need java for some parts.
I have managed to find a specific word in one text file, but i need to look for a specific word, in multiple text files. all of the files are ".txt" and they are in the same folder but each of them with different names. I have written the following code: but i receive an error that i don't...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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,...
| |
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...
|
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...
|
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...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |