I'm trying to paste in a txt block but I always get an error no matter how hard I try
the copy part is already resolved but pasting in a txt not yet
import pyperclip
with open('conta.txt', 'w+') as f:
conteudo = f.write()
pyperclip.paste(str(conteudo))
Think it's more like this:
import pyperclip
with open('conta.txt', 'w+') as f:
f.write( pyperclip.paste() )
Related
I'm trying to replace all HTML codes in my HTML file in a for Loop (not sure if this is the easiest approach) without changing the formatting of the original file. When I run the code below I don't get the codes replaced. Does anyone know what could be wrong?
import re
tex=open('ALICE.per-txt.txt', 'r')
tex=tex.read()
for i in tex:
if i =='õ':
i=='õ'
elif i == 'ç':
i=='ç'
with open('Alice1.replaced.txt', "w") as f:
f.write(tex)
f.close()
You can use html.unescape.
>>> import html
>>> html.unescape('õ')
'õ'
With your code:
import html
with open('ALICE.per-txt.txt', 'r') as f:
html_text = f.read()
html_text = html.unescape(html_text)
with open('ALICE.per-txt.txt', 'w') as f:
f.write(html_text)
Please note that I opened the files with a with statement. This takes care of closing the file after the with block - something you forgot to do when reading the file.
I have the following code:
import re
#open the xml file for reading:
file = open('path/test.xml','r+')
#convert to string:
data = file.read()
file.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
file.close()
where I'd like to replace the old content that's in the file with the new content. However, when I execute my code, the file "test.xml" is appended, i.e. I have the old content follwed by the new "replaced" content. What can I do in order to delete the old stuff and only keep the new?
You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace:
import re
myfile = "path/test.xml"
with open(myfile, "r+") as f:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
f.truncate()
The other way is to read the file then open it again with open(myfile, 'w'):
with open(myfile, "r") as f:
data = f.read()
with open(myfile, "w") as f:
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
Neither truncate nor open(..., 'w') will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4).
By the way, this is not really related to Python. The interpreter calls the corresponding low level API. The method truncate() works the same in the C programming language: See http://man7.org/linux/man-pages/man2/truncate.2.html
file='path/test.xml'
with open(file, 'w') as filetowrite:
filetowrite.write('new content')
Open the file in 'w' mode, you will be able to replace its current text save the file with new contents.
Using truncate(), the solution could be
import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
#convert to string:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
f.truncate()
import os#must import this library
if os.path.exists('TwitterDB.csv'):
os.remove('TwitterDB.csv') #this deletes the file
else:
print("The file does not exist")#add this to prevent errors
I had a similar problem, and instead of overwriting my existing file using the different 'modes', I just deleted the file before using it again, so that it would be as if I was appending to a new file on each run of my code.
See from How to Replace String in File works in a simple way and is an answer that works with replace
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
in my case the following code did the trick
with open("output.json", "w+") as outfile: #using w+ mode to create file if it not exists. and overwrite the existing content
json.dump(result_plot, outfile)
Using python3 pathlib library:
import re
from pathlib import Path
import shutil
shutil.copy2("/tmp/test.xml", "/tmp/test.xml.bak") # create backup
filepath = Path("/tmp/test.xml")
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
Similar method using different approach to backups:
from pathlib import Path
filepath = Path("/tmp/test.xml")
filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
In that part of code I make the files txt and its working
import sys
for i in range(6):
file = open('teste{:d}.txt'.format(i), 'a')
sys.stdout = file
And now the problem, the files were created but in this part of code it didnt work, i can compile but the files are empty
for i in range(1,6):
f=open('100K_Array_{:d}.txt'.format(i), 'r')
alist = f.readlines()
quickSort(alist)
print(alist)
f.close()
It appears to me that you haven't closed your output file properly. You should either use
with open('teste{:d}.txt', 'a') as file:
...
in which case with statement will handle closing the file for you. Otherwise you need to add file.close() to your current code.
I am trying to loop through all CSV files in a directory, do a find/replace, and save the results to the same file (same name). It seems like this should be easy, but I seem to be missing something here. Here is the code that I'm working with.
import glob
path = 'C:\\Users\\ryans\\OneDrive\\Desktop\\downloads\\Products\\*.csv'
for fname in glob.glob(path):
print(str(fname))
with open(str(fname), "w") as f:
newText = f.read().replace('|', ',').replace(' ', '')
f.write(newText)
I came across the link below, and tried the concepts listed there, but nothing has worked so far.
How to open a file for both reading and writing?
You need to open the file using 'r+' instead of 'w'. See below:
import glob
path = 'C:\\Users\\ryans\\OneDrive\\Desktop\\downloads\\Products\\*.csv'
for fname in glob.glob(path):
print(str(fname))
with open(str(fname), "r+") as f:
newText = f.read().replace('|', ',').replace(' ', '')
f.write(newText)
Here is the final (working) solution.
import glob
import fileinput
path = 'C:\\Users\\ryans\\OneDrive\\Desktop\\downloads\\Products\\*.csv'
for fname in glob.glob(path):
#print(str(fname))
with open(fname, 'r+') as f:
text = f.read().replace(' ', '')
f.seek(0)
f.write(text)
f.truncate()
Thanks for the tip, agaidis!!
it does work if I type this on python shell
>>> f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
>>> f.read()
'plpw eeeeplpw eeeeplpw eeee'
>>> f.close()
but if I create a python program, i doesn't work.
import os
f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
f.read()
f.close()
i saved this piece of code by using text editor.
if I execute this program in python shell, it shows nothing.
please tell me why..
In the interactive prompt, it automatically prints anything a function call returns. That means the return value of f.read() is printed automatically. This won't happen when you put it in a program however, so you will have to print it yourself to have it show up.
import os
f = open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
print f.read() # use print(f.read()) in Python 3
f.close()
Another suggestion I would make would be to use a with block:
import os
with open(os.path.join(os.getcwd(), 'test1.txt'), 'r') as f:
print f.read()
This means that you won't have to worry about manually closing the file afterwards.