473,750 Members | 2,533 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

merging files, each file in a new line

9 New Member
I have this code to merge files. the files language is persian. it merges them but I want each file to be written in a new line. for example if I have 9 files, the output should be 9 lines. each line is one file. the problem is that I don't know where to put replace('\n', " ") to omit newlines of a file and where to add '\n' to go to the next file.

Expand|Select|Wrap|Line Numbers
  1. import os,shutil
  2. path = 'فناوري'
  3. f=open("wwww.txt","a", encoding = 'utf-8')
  4. for r,d,fi in os.walk(path):
  5.     for files in fi:
  6.         if files.endswith(".txt"):                         
  7.             g=open(os.path.join(r,files), encoding = 'utf-8')
  8.             shutil.copyfileobj(g,f)
  9.             g.close()
  10. f.close()
Mar 11 '15 #1
8 2209
bvdet
2,851 Recognized Expert Moderator Specialist
Given a list of filenames, create a string from the contents of each file. You can then write the string to your output file.
Expand|Select|Wrap|Line Numbers
  1. >>> files = ["text1.txt", "text2.txt"]
  2. >>> output = "\n".join([",".join([line.strip() for line in open(fn).readlines()]) for fn in files])
  3. >>> output
  4. 'abcdef,xyz\n123456,1098'
  5. >>>
Mar 11 '15 #2
thistle
9 New Member
I added 2 lines to the code. it was working some hours ago, but now it doesn't work. I don't know the problem!!!!!!!! !!!can anybody help?
Expand|Select|Wrap|Line Numbers
  1. import os,shutil
  2. path = 'فناوري'
  3. f=open("wwww.txt","a", encoding = 'utf-8')
  4. for r,d,fi in os.walk(path):
  5.     for files in fi:
  6.         if files.endswith(".txt"):
  7.              g=open(os.path.join(r,files), encoding = 'utf-8')
  8.              for line in g:
  9.                  f.write(line.strip('\n') + ' ')
  10.                  shutil.copyfileobj(g,f)
  11.                  f.write('\n')
  12.                  g.close()
  13. f.close()
Mar 11 '15 #3
bvdet
2,851 Recognized Expert Moderator Specialist
Please provide the error traceback or describe the issue.
Mar 11 '15 #4
bvdet
2,851 Recognized Expert Moderator Specialist
Just noticed something. Eliminate the for loop on the file object g. shutil.copyfile obj() copies all of the file contents, not just the current line. Something like this:
Expand|Select|Wrap|Line Numbers
  1.         if files.endswith(".txt"):
  2.             g=open(os.path.join(r,files)) #, encoding='utf-8')
  3.             shutil.copyfileobj(g,f)
  4.             f.write('\n')
  5.             g.close()
Mar 11 '15 #5
thistle
9 New Member
I want each file (which has some lines) to be written in just one line. so I need to omit newlines between them. and the to write the next file as the next line I need to add '\n'. so I cant eliminate for loop. If I eliminate it of course it merges them but there are a lot of lines. each file should be = one line
Mar 11 '15 #6
bvdet
2,851 Recognized Expert Moderator Specialist
Did you try the code in my first reply? That's the functionality you seek, or is it not? It uses a comma delimiter for lines in a file, but you can change that to whatever character you want.
Mar 11 '15 #7
thistle
9 New Member
I started python recently. sorry for so much questions. open (fn)reads a file but I have a folder which contains 10 files. what should I write instead of fn so that it reads the folder. I know I have to split the folder first with os.listdir (folder) but then what?
Mar 11 '15 #8
bvdet
2,851 Recognized Expert Moderator Specialist
Create the list of file names first. Then iterate on the list of file names.
Expand|Select|Wrap|Line Numbers
  1. import os
  2. path = r"X:\temp\macro\test"
  3. files = os.listdir(path)
  4. outputList = []
  5. for fn in files:
  6.     if fn.endswith("txt"):
  7.         outputList.append(",".join([line.strip() for line in open(os.path.join(path, fn)).readlines()]))
  8. output = "\n".join(outputList)
  9. print output
Mar 11 '15 #9

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

Similar topics

2
2756
by: Aaron Deskins | last post by:
Hello everyone, I'm relatively new to Python and am trying to write some scripts. I've written a program (with the help of a friend) to search a text file line by line for a certain section of information and then process some of that information. This was on machines with Python 2.2.1 and 2.3.2. When I try the same program on another machine using Python 2.1.2 and another with Python 1.5.2, the script does not work. I've isolated the...
40
61226
by: Abby | last post by:
My .dat file will contain information like below. /////////// First 0x04 0x05 0x06 Second 0x07
5
22503
by: Piotr | last post by:
I have a qestion about reading file in C++. How can I read a file line by line (i.e. putting a line ends wtih \n in a string) I tried the following, it does read the file, but it does not read it line by line. ifstream infile (fileName.c_str()); string buffer;
5
6214
by: grinder | last post by:
first off, i am an extreme newbie to C. i am an undergrad research assistant and i have been shifted to a project that involves building a fairly involved c program. The part that i am stuck on now is as follows: - i am trying to write code that will take any number of text inputs (names of other text files) and put them into a file line-by-line at the users request. meaning, i want the user to be able to type the strings and enter them...
8
10395
by: Jared Wiltshire | last post by:
Hi, I've written the following code to copy one files contents line by line into another file. However I'm a bit dubious about using the infinite loop to do this. ifstream infile("File1.txt"); ofstream outfile("File2.txt"); string line = ""; while (true) {
9
5210
by: Adi | last post by:
Hello eveyone, I wanna ask a very simple question here (as it was quite disturbing me for a long time.) My problem is to read a file line by line. I've tried following implementations but still facing problems: Assume that FILE* filePointer; unsigned char lineBuffer;
2
2548
by: Taras_96 | last post by:
Hi all, I've been using debug_backtrace() for a while to provide stack traces for a custom logging function. Today was the first time I've got the following error: "Notice: Undefined index: file in E:\webroot\lib\errors.php on line 341 Notice: Undefined index: line in E:\webroot\lib\errors.php on line
6
32918
by: Thomas Kowalski | last post by:
Hi, currently I am reading a huge (about 10-100 MB) text-file line by line using fstreams and getline. I wonder whether there is a faster way to read a file line by line (with std::string line). Is there some way to burst read the whole file and later "extract" each line? Thanks in advance, Thomas Kowalski
6
9309
by: kimiraikkonen | last post by:
Hi, I want to save all the item content of a listbox line by line into a simple text file then recall them when my project is opened. For example listbox1 contains: That - item1 Group -item2 Is -item3 Really -item4
12
13733
by: freeseif | last post by:
Hi programmers, I want read line by line a Unicode (UTF-8) text file created by Notepad, i don't want display the Unicode string in the screen, i want just read and compare the strings!. This code read ANSI file line by line, and compare the strings What i want Read test_ansi.txt line by line
0
8838
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
9583
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
9396
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...
0
9256
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
8263
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...
0
6081
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();...
0
4716
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...
0
4888
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2226
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.