How can i both read and modify a .txt file in python?
I am trying to write a programme using which i modify a text file using given user input. But if i use 'r' within open, it only reads.
I have tried:
sanskrit = open("sanskrit.txt","r")
sans = sanskrit.read()
print(sans)
sanskrit.close
Error i got:
Traceback (most recent call last):
File "/home/pi/Desktop/AnuragEK/coding/try.py/", line 3,in
sans = sanskrit.read()
Can anyone help me?
Thanks in advance.
If you are trying to both read and write from/to a file, you should use the mode 'r+' instead of 'r'. There are a few other modes for doing this but 'r+' is probably the one you want.
Related
I am making a full python keylogger. It undergoes a simple processes. First store keystrokes inside a file on startup. Next, find the file and send the file across WiFi. Lastly, shutdown. For this to work I need to make a file for the keylogger to send the keystroke information to. I tried using:
open('myfile', 'w+')
This will create my file but how do I place my file into a certain place?
Extra Information:
Python 3.7x
You can add the path to the filename:
open('/users/myname/myfile.txt', 'w+')
open('C:\\Public\\myfile.txt', 'w+')
Or, you can change your current directory:
import os
os.chdir('/tmp/')
open('myfile.txt', 'w+')
Both should work! Happy Coding!
I believe you're looking for a file path. The open() function in Python takes a file path and the read/write mode. In most programming languages and operating systems use dots and slashes to represent paths. Currently your script opens a file called "myfile" in the directory (folder) that your script is executing in. However, if you wanted to place that file one directory higher on the file tree, you could write the function as follows:
// Linux
open('../myfile', 'w+')
// Windows
open('..\myfile', 'w+')
Unfortunately, this method does require a knowledge of the system filetree.
If this answer helped you, I'd appreciate if you'd give it an upvote or mark it as correct!
I have a python program and it seems that whenever I open it with this line of code active:
content = open('Word_list.txt').read().splitlines() it just closes itself (by open I mean double clicking it from file explorer, works fine every other way). I tried with a small list variable and my program works file when it's like that so I need to convert a 4MB file (4,250,000 lines) into a python list variable. Is there any way to do that and will there be any slowdowns because of what i'm doing here?
Oh, and I should mention that I tried other ways of importing the text file (for loops and whatnot) and that seemed to crash instantly too. Thanks!
Because you are running it through Explorer the window is closing before you can see an error message, so add some error handling code:
try:
content = open('Word_list.txt').read().splitlines()
except Exception as exc:
import traceback
print(traceback.format_exc())
input()
I managed to use Notepad++ and their macro system to put the required " ",'s over all of the words, completing my objecting using another program instead of python.
I saved a text file to my desktop named "test.txt" within the file I wrote only my name, David. Then, I opened terminal and opened python 3.7.1 and wrote the following code in attempt to see my name, David, populate:
open("/Users/David/Desktop/test.txt,"r")
However, I receive the following error message:
SyntaxError: EOL while scanning string literal
Does anyone know how I can avoid this error and have my name, David, read from the test.txt file on my desktop? Or am I going about this completely wrong?
As #Matt explained, you are missing quotes.
You can follow below approach to open file and read from it.
myfile = open("/Users/David/Desktop/test.txt","r") #returns file handle
myfile.read() # reading from the file
myfile.close() # closing the file handle, to release the resources.
For more information on how to do read/write operations on file
You are missing a quotation mark, after your file path. It should look like this:
open("/Users/David/Desktop/test.txt","r")
^ This quotation mark
This will open the file correctly, however you will still need to actually read from it.
You are missing the other quotations as the others have mentioned. Try using the with open statement, as it handles your resources for you, meaning you don't need to specify .close()
with open("/Users/David/Desktop/test.txt", "r") as file:
file.read()
you can use with which will close the file automatically as you come out of the block and put your Directory link
with open(r"Directory_link", "r") as file1:
FileContent = file1.read()
print(FileContent)
I wrote some code to pull certain lines from a large text file and noticed some strange things missing, so I ran the following code to make sure the for loop was actually hitting every line in the file:
xf=open("bigFile.txt", r)
xxf=open("newFile.txt",w)
for line in xf:
xxf.write(line)
This ends up not copying all the lines for some reason. Could anyone tell me what I'm not understanding or doing wrong? It ends up only making a file about 60-70% as big as it should be? Any insight would be greatly appreciated.
EDIT: Thanks for the input skrrgwasme & Shreevardhan. To clarify, my ultimate goal is not just to copy the file, in my working code I put some comparison operators before writing the line, for example:
for line in xf:
firstChar=line[:1]
if firstChar==1:
xxf.write(line)
That is why I am using the "for line in file". Should I do this some other way?
To copy a file, it's better to use functions from shutil module like copyfile(), copy(), or copy2().
For example
from shutil import copyfile, copy2
copyfile('bigFile.txt', 'newFile.txt')
or
copy2('bigFile.txt', 'newFile.txt')
You need to close your file. There's no guarantee that buffers you're writing into are being flushed to disk before your script exits. You can do this very easily by using a context manager:
with open("bigFile.txt") as xf, open("newFile.txt", "w") as xxf:
for line in xf:
xxf.write(line)
In your current code, you would write xf.close() and xxf.close(), but using a context manager like this will handle it for you, and even close the files if an exception occurs.
Also, if you really are simply copying the file, you can also use shutil.copyfile().
I've created a txt file by Microsoft Word and saved it as texta.txt in a folder untitled. I've also saved a python file as texti.py in the same folder untitled.
When going back to Wing IDE, i typed the following:
infile = open('texta.txt')
lines = infile.readlines()
and it returned:
Traceback (most recent call last):
File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 2, in <module>
if __name__ == '__main__':
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
builtins.UnicodeDecodeError: 'ascii' codec can't decode byte 0xd5 in position 192: ordinal not in range(128)
i want to open the file (text), and print it into the python shell.
When you save a file as .txt, you should specify the encoding instead of letting the editor choose for you, and not tell you. LibreOffice has two text SaveAs options: 'Text (.txt)' and 'Text - choose encoding (.txt)'. MS Word should also have an option to select the encoding. If not, get an editor that does. And select UTF8 unless you have a reason to select otherwise.
The particular error message suggests to me that your text file is not utf8. A likely alternative is 'latin1'. If so, b'\xd5'.decode('latin1') == 'Õ'. If 'Õ' is the 195th char in your file, use encoding=latin1. If not, you could guess something else. Or reopen with MS Word on the same machine and save with a known encoding.