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. -
import os,shutil
-
path = 'فناوري'
-
f=open("wwww.txt","a", encoding = 'utf-8')
-
for r,d,fi in os.walk(path):
-
for files in fi:
-
if files.endswith(".txt"):
-
g=open(os.path.join(r,files), encoding = 'utf-8')
-
shutil.copyfileobj(g,f)
-
g.close()
-
f.close()
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. - >>> files = ["text1.txt", "text2.txt"]
-
>>> output = "\n".join([",".join([line.strip() for line in open(fn).readlines()]) for fn in files])
-
>>> output
-
'abcdef,xyz\n123456,1098'
-
>>>
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? -
import os,shutil
-
path = 'فناوري'
-
f=open("wwww.txt","a", encoding = 'utf-8')
-
for r,d,fi in os.walk(path):
-
for files in fi:
-
if files.endswith(".txt"):
-
g=open(os.path.join(r,files), encoding = 'utf-8')
-
for line in g:
-
f.write(line.strip('\n') + ' ')
-
shutil.copyfileobj(g,f)
-
f.write('\n')
-
g.close()
-
f.close()
bvdet 2,851
Recognized Expert Moderator Specialist
Please provide the error traceback or describe the issue.
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: - if files.endswith(".txt"):
-
g=open(os.path.join(r,files)) #, encoding='utf-8')
-
shutil.copyfileobj(g,f)
-
f.write('\n')
-
g.close()
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
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.
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?
bvdet 2,851
Recognized Expert Moderator Specialist
Create the list of file names first. Then iterate on the list of file names. - import os
-
path = r"X:\temp\macro\test"
-
files = os.listdir(path)
-
outputList = []
-
for fn in files:
-
if fn.endswith("txt"):
-
outputList.append(",".join([line.strip() for line in open(os.path.join(path, fn)).readlines()]))
-
output = "\n".join(outputList)
-
print output
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
by: Abby |
last post by:
My .dat file will contain information like below.
///////////
First
0x04
0x05
0x06
Second
0x07
|
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;
|
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...
|
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)
{
| |
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;
|
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
|
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
|
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
|
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
|
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: 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...
|
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: 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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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...
| | |