473,413 Members | 2,058 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,413 software developers and data experts.

merging files, each file in a new line

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 2186
bvdet
2,851 Expert Mod 2GB
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
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 Expert Mod 2GB
Please provide the error traceback or describe the issue.
Mar 11 '15 #4
bvdet
2,851 Expert Mod 2GB
Just noticed something. Eliminate the for loop on the file object g. shutil.copyfileobj() 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
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 Expert Mod 2GB
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
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 Expert Mod 2GB
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
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...
40
by: Abby | last post by:
My .dat file will contain information like below. /////////// First 0x04 0x05 0x06 Second 0x07
5
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...
5
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...
8
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");...
9
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...
2
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:...
6
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)....
6
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 ...
12
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...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
marktang
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,...
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...
0
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...
0
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...
0
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...

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.