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)
Related
This is my original .txt data:
HKEY_CURRENT_USER\SOFTWARE\7-Zip
HKEY_CURRENT_USER\SOFTWARE\AppDataLow
HKEY_CURRENT_USER\SOFTWARE\Chromium
HKEY_CURRENT_USER\SOFTWARE\Clients
HKEY_CURRENT_USER\SOFTWARE\CodeBlocks
HKEY_CURRENT_USER\SOFTWARE\Discord
HKEY_CURRENT_USER\SOFTWARE\Dropbox
HKEY_CURRENT_USER\SOFTWARE\DropboxUpdate
HKEY_CURRENT_USER\SOFTWARE\ej-technologies
HKEY_CURRENT_USER\SOFTWARE\Evernote
HKEY_CURRENT_USER\SOFTWARE\GNU
And I need to have a new file where the new lines contain only part of those strings, like:
7-Zip
AppDataLow
Chromium
Clients
...
how to do it in python?
Try this:
## read file content as string
with open("file.txt", "r") as file:
string = file.read()
## convert each line to list
lines = string.split("\n")
## write only last part after "\" in each line
with open("new.txt", "w") as file:
for line in lines:
file.write(line.split("\\")[-1] + "\n")
One approach would be to read the entire text file into a Python string. Then use split on each line to find the final path component.
with open('file.txt', 'r') as file:
data = file.read()
lines = re.split(r'\r?\n', data)
output = [x.split("\\")[-1] for x in lines]
# write to file if desired
text = '\n'.join(output)
f_out = open('output.txt', 'w')
f_out.write(text)
f_out.close()
I am currently writing an script which is replacing the line of a file with the content of two other files and right after writes the new line to a new file. But when running my script only the content of the first file was replaced with the content of the line.
My code:
with open('file1.txt','r') as file1, open('file2.txt','r') as file2, \
open('original.txt','r') as original:
for lines in original:
with open('sample.txt','w') as sample:
for line in file1:
sample.write(lines.replace(line,''))
sample.close()
with open('sample.txt','w') as sample:
for line in file2:
sample.write(lines.replace(line,''))
sample.close()
Content of my file1:
Python
Content of my file2:
Pascal
Content of my original file:
I Python like Pascal cookies
Content of the new file after running my script:
I like Pascal cookies
What the content of the new file should actually look like after running my script:
I like cookies
Am I doing something wrong? Could someone tell me what's wrong and help solve this problem?
The problem that your replaces are targeting always to the original value, lines so your multiple changes do not accumulate.
So for example
a = 'ciao'
a.replace('i', 'I')
print(a)
will print ciao since replace return a new string (strings are immutable) object which you need to store in some variable otherwise... just useless
Here a solution
with open('./file1','r') as file1, open('./file2','r') as file2, open('original','r') as original:
with open('sample.txt','w') as sample:
a = original.read()
b = a.replace(file1.read(), '')
c = b.replace(file2.read(), '')
sample.write(c)
with open('sample.txt', 'r') as fd: print(fd.read())
Output
I like cookies
Here's another example using list
#!/usr/bin/env python3.7
with(open('file1','r') as f1,
open('file2', 'r') as f2,
open('original', 'r') as orig,
open('new.txt', 'w') as newfile):
origtxt = orig.read()
tmplist = [f1.read(),f2.read()]
for i in range(len(tmplist)):
origtxt = origtxt.replace(f'{tmplist[i]} ','')
newfile.write(origtxt)
I didn't account for new lines in the above.
#!/usr/bin/env python3.7
with open('file1','r') as f1, \
open('file2', 'r') as f2, \
open('original', 'r') as orig, \
open('new.txt', 'w') as newfile:
origtxt = orig.read()
tmplist = f'{f1.read()}'.split('\n') + f'{f2.read()}'.split('\n')
print(tmplist)
for i in range(len(tmplist)):
origtxt = origtxt.replace(f'{tmplist[i]}', '')
origtxt = origtxt.replace(' ',' ')
#newfile.write(origtxt)
print(origtxt)
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 a large 11 GB .txt file with email addresses. I would like to save only the strings till the # symbol among each other. My output only generate the first line.I have used this code of a earlier project. I would like to save the output in a different .txt file. I hope someone could help me out.
my code:
import re
def get_html_string(file,start_string,end_string):
answer="nothing"
with open(file, 'rb') as open_file:
for line in open_file:
line = line.rstrip()
if re.search(start_string, line) :
answer=line
break
start=answer.find(start_string)+len(start_string)
end=answer.find(end_string)
#print(start,end,answer)
return answer[start:end]
beginstr=''
end='#'
file='test.txt'
readstring=str(get_html_string(file,beginstr,end))
print readstring
Your file is quite big (11G) so you shouldn't keep all those strings in memory. Instead, process the file line by line and write the result before reading next line.
This should be efficient :
with open('test.txt', 'r') as input_file:
with open('result.txt', 'w') as output_file:
for line in input_file:
prefix = line.split('#')[0]
output_file.write(prefix + '\n')
If your file looks like this example:
user#google.com
user2#jshds.com
Useruser#jsnl.com
You can use this:
def get_email_name(file_name):
with open(file_name) as file:
lines = file.readlines()
result = list()
for line in lines:
result.append(line.split('#')[0])
return result
get_email_name('emails.txt')
Out:
['user', 'user2', 'Useruser']
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.