Is there a way to concatenate two text file without writting the result into a another file, but just store it in a variable?
What I'm looking for is something like
my_fun(cat(file1,file2))
where my_fun will read the result of the concatenation cat and use it as if it was a real text file.
In other word, I'd like to do
with open(my_fileOut,'w') as outfile:
for file in [file_1,file_2]:
with open(file,'r') as infile:
for line in infile:
outfile.write(line)
and remplace my_fileOut with a variable and therefore not make outfile.write(line) but store the result in memory
Thanks a lot in advance for any help or piece of advice,
Regards
PS : Sorry if my english is not very good
It looks like you just want to write a file in the end. So why not?:
def cat(f1, f2):
with open(f1, 'r') as f:
f1txt = f.read()
with open(f2, 'r') as f:
f2txt = f.read()
return f1txt + f2txt
def my_fun(f3, text):
with open(f3, 'w') as f:
f.write(text)
out = '/path/to/some/file'
file1 = '/path/to/file1'
file2 = '/path/to/file2'
my_fun(cat(file1, file2))
This will read all the data inside file1, then file2 and then add all the data from file2 to the end of the file1 data. If you mean to concatenate another way, please specify.
You can use itertools.chain():
from itertools import chain
def my_fun(f):
for line in f:
print(line.rstrip())
with open('file1') as file1, open('file2') as file2:
my_fun(chain(file1, file2))
This works because file objects are iterable, and chain() effectively concatenates one or more iterables.
Related
The problem is I have this text, csv file which is missing commas and I would like to insert it in order to run the file on LaTex and make a table. I have a MWE of a code from another problem which I ran and it did not work. Is it possible someone could guide me on how to change it.
I have used a Python code which provides a blank file, and another one which provides a blank document, and another which removes the spaces.
import fileinput
input_file = 'C:/Users/Light_Wisdom/Documents/Python Notes/test.txt'
output= open('out.txt','w+')
with open('out.txt', 'w+') as output:
for each_line in fileinput.input(input_file):
output.write("\n".join(x.strip() for x in each_line.split(',')))
text file contains more numbers but its like this
0 2.58612
0.00616025 2.20018
0.0123205 1.56186
0.0184807 0.371172
0.024641 0.327379
0.0308012 0.368863
0.0369615 0.322228
0.0431217 0.171899
Outcome
0.049282, -0.0635003
0.0554422, -0.110747
0.0616025, 0.0701394
0.0677627, 0.202381
0.073923, 0.241264
0.0800832, 0.193697
Renewed Attempt:
with open("CSV.txt","r") as file:
new = list(map(lambda x: ''.join(x.split()[0:1]+[","]+x.split()[0:2]),file.readlines()))
with open("New_CSV.txt","w+") as output:
for i in new:
output.writelines(i)
output.writelines("\n")
This can be using .split and .join by splitting the line into a list and then joining the list separated by commas. This enables us to handle several subsequent spaces in the file:
f1 = open(input_file, "r")
with open("out.txt", 'w') as f2:
for line in f1:
f2.write(",".join(line.split()) + "\n")
f1.close()
You can also use csv to handle the writing automatically:
import csv
f1 = open(input_file, "r")
with open("out.txt", 'w') as f2:
writer = csv.writer(f2)
for line in f1:
writer.writerow(line.split())
f1.close()
I have the following code, where I read an input list, split it on its backslash, and then append the variable evid to the evids array. Next, I open a file called evids.txt and write the evids to that file. How do I speed up/reduce the number of lines in this code? Thanks.
evids = []
with open('evid_list.txt', 'r') as infile:
data = infile.readlines()
for i in data:
evid = i.split('/')[2]
evids.append(evid)
with open('evids.txt', 'w') as f:
for i in evids:
f.write("%s" % i)
with open('evid_list.txt', 'r') as infile, open('evids.txt', 'w') as ofile:
for line in infile:
ofile.write('{}\n'.format(line.split('/')[2]))
I have two text files and I want to write out two new text files according to whether there is a common section to each line in the two original text files.
The format of the text files is as follows:
commontextinallcases uniquetext2 potentiallycommontext uniquetext4
There are more than 4 columns but you get the idea. I want to check the 'potentiallycommontext' part in each text file and if they are the same write out the whole line of each text file to a new text file for each with its own unique text still in place.
Spliting it is fairly easy just using the .split() command when reading it in. I have found the following code:
with open('some_file_1.txt', 'r') as file1:
with open('some_file_2.txt', 'r') as file2:
same = set(file1).intersection(file2)
same.discard('\n')
with open('some_output_file.txt', 'w') as file_out:
for line in same:
file_out.write(line)
But I am not sure this would work for my case where I need to split the lines. Is there a way to do this I am missing?
Thanks
I don't think, that this set-approach is suitable for your case.
I'd try like
with open('some_file_1.txt', 'r') as file1, open('some_file_2.txt', 'r') as file2, open('some_output_file.txt', 'w') as file_out:
for line1, line2 in zip(file1, file2):
if line1.split()[2] == line2.split()[2]:
file_out.write(line1)
file_out.write(line2)
There might be shorter solutions but this should work
PCT_IDX = _ # find which index of line.split() corresponds to potentiallycommontext
def lines(filename):
with open(filename, 'r') as file:
for line in file:
line = line.rstrip('\n')
yield line
lines_1 = lines('some_file_1.txt')
lines_2 = lines('some_file_2.txt')
with open('some_output_file.txt', 'w') as file_out:
for (line_1, line_2) in zip(lines_1, lines_2):
maybe_cmn1 = line_1.split()[PCT_IDX]
maybe_cmn2 = line_2.split()[PCT_IDX]
if maybe_cmn1 == maybe_cmn2:
file_out.write(line_1)
file_out.write(line_2)
I have a file 'master.sql' that contains:
a.b.c
d.e.f
g.h.i
and I want to write on 'databases.sql' just the first letters, like this:
a
d
g
Here is my code, but returns just the last letter, the 'g'.
with open ('master.sql', 'r') as f:
for line in f:
x=(line.split('.')[0])
with open('databases.sql', 'w') as f:
f.write(str(x))
How can I fix this?
You'll need to write your data as you read it, otherwise you're not going to be able to do what you want. Fortunately, with allows you to open multiple files concurrently. This should work for you.
with open ('master.sql', 'r') as f1, open('databases.sql', 'w') as f2:
for line in f1:
f2.write(line.split('.')[0] + '\n')
Don't forget to write a newline, because file.write doesn't add one automatically.
Using list:
x = []
with open('master.sql', 'r') as f:
for line in f.readlines():
x.append(line.split('.')[0])
with open('databases.sql', 'w') as f:
for word in x:
f.write(str(word)+'\n')
The variable x receives all values, but each loop overwrite the last value. Hence, the result is 'g'.
To save all values you can do like this:
lst = []
with open ('master.sql', 'r') as f:
for line in f:
lst.append(line.split('.')[0])
x = '\n'.join(lst)
with open('databases.sql', 'w') as f:
f.write(x)
SO basically what I am trying to do is that I am trying to make it so I can read a file line by line, and then have a certain text added after the text displayed
For Ex.
Code:
file = open("testlist.txt",'w')
file2 = open("testerlist.txt",'r+')
//This gives me a syntax error obviously.
file.write1("" + file + "" + file2 + "")
Textlist
In my testlist.txt it lists as:
os
Testerlist
In my testerlist.txt it lists as:
010101
I am trying to copy one text from one file and read another file and add it to the beginning of a new file for ex.[accounts.txt].
My End Result
For my end result I am trying to have it be like:
os010101
(btw I have all the correct code, its just that I am using this as an example so if I am missing any values its just because I was to lazy to add it.)
You can use file.read() to read the contents of a file. Then just concatenate the data from two files and write to the output file:
with open("testlist.txt") as f1, open("testerlist.txt") as f2, \
open("accounts.txt", "w") as f3:
f3.write(f1.read().strip() + f2.read().strip())
Note that 'mode' is not required when opening files for reading.
If you need to write the lines in particular order, you could use file.readlines() to read the lines into a list and file.writelines() to write multiple lines to the output file, e.g.:
with open("testlist.txt") as f1, open("testerlist.txt") as f2, \
open("accounts.txt", "w") as f3:
f1_lines = f1.readlines()
f3.write(f1_lines[0].strip())
f3.write(f2.read().strip())
f3.writelines(f1_lines[1:])
Try with something like this:
with open('testlist.txt', 'r') as f:
input1 = f.read()
with open('testerlist.txt', 'r') as f:
input2 = f.read()
output = input1+input2
with open("accounts.txt", "a") as myfile:
myfile.write(output)