How to open a text file from my desktop while using python 3.7.1 in Terminal - python-3.x

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)

Related

.txt file is opening but prints nothing

I'm trying to open a text file and print it as a string. I've made sure there is text in the .txt file but when I run the code it just prints an empty space, I don't know what to do at this point since I couldn't find anything that could help me with my problem.
with open('test.txt', 'r') as file:
data = file.read().rstrip()
print(data)
When things aren't opening check the following:
You wrote exactly the same in your code as the one you saved. "file.txt" is not the same as "File.txt" for Python (same goes for accents and special characters).
The file you are trying to read is in the same directory. If your code is at users/bla/documents/another_folder and you just pass the name of the file to your code, then the file must be at users/bla/documents/another_folder too. If not, be shure to add it into the string path as "path/to/your/file/file.txt"
Make sure that the extension .txt is the same as your file.
If you checked that but everything seems correct, try:
with open(path_to_file) as f:
contents = f.readlines()
And see if "contents" has something.
I think it is better if you use open("file.txt","r") function to do it. So your code will be like this:
file=open("test.txt","r")
data=file.read().strip()
print(data)

How to place a new file in a certian place on hard drive (python)

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!

How do I convert a file from plain text to a list variable?

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.

opening a gzipped fil, characters following three pipes ("|||") are not visible

My input file is a gzipped file containing genomic information. I'm trying to parse the content on a line-by-line basis and have run into a strange problem.
Any given line looks something like this:
AC=26;AF=0.00519169;AN=5008;NS=2504;DP=17308;EAS_AF=0;AMR_AF=0.0072;AFR_AF=0.0015;EUR_AF=0.0109;SAS_AF=0.0082;AA=A|||;VT=SNP
However, when I print out what is being read in...
import gzip
with gzip.open(myfile.gz, 'rt') as f:
for line in f:
print(line)
The line looks like this:
AC=26;AF=0.00519169;AN=5008;NS=2504;DP=17308;EAS_AF=0;AMR_AF=0.0072;AFR_AF=0.0015;EUR_AF=0.0109;SAS_AF=0.0082;AA=A|||
Whatever information comes after the "|||" has been truncated.
Moreover, I can't even search the lines for strings that follow the "|||" (e.g. "VT=SNP" in line always returns False) I also can't line.strip("|||")
Any advice on what is causing this or what I need to look at?
Thank you for any help
EDIT: ok, it looks like there was something wrong with the gzip file. I uncompressed it and the script ran fine. Then I recompressed it and the script again ran fine (using gzip.open). Is there any straightforward way to compare the two compressed files (ie, the one that doesn't get read properly vs the one that works) so that I might get a hint at the root cause?

Python copy and paste path file from Windows Explorer into variable

I developed a software in Python3.4 which has as input a config file with a set of variables and some of them are paths.
I have a problem with the separator in the file path name.
I know I can put a "r" in front of the string or use the double backslash or the slash so to have a raw string, but because this software will be used by other users and the average one is just a "copy and paste" guy, I don't want they manipulate the file name.
So the users have just to copy from the Windows Explorer the file path and paste into the config file, something like:
path_variable = "C:\Users\home\room\table.txt"
and I want to write a function that modify it so can be used.
How can I do it? If I leave the string in this way I obtain an unicode error because of \U...
Thanks a lot,
Ciccio
Update
The config file is not a python file but just a .txt file within the variables and their values:
var_name = var_val
path_variable = "C:\Users\home\room\table.txt"
height = 20
plot_write_variable = ["y", "n"]
This is just a temporary solution until I finalize the GUI. This file must be really easy to understand and the software has to be used by people don't have any knowledge of Python or programming. The final user has just to change the variables value and click on the executable file to run the program and nothing else. For this reason I want to avoid as much as possible the use of any python command.
To read the config file I use this function:
import imp
def read_inputFile(path):
file = open(path)
variables = imp.load_source('data', '', file)
file.close()
return variables
Your config files don't have to be written in Python. You could use configparser, which so far as I can tell does not interpret backslashes specially.
This may require some re-working of your logic for the config file. Instead of importing the config file directly with an import statement, you would parse it with the configparser module. You may also need to adjust the syntax of your config file to match what configparser is expecting.
You say that your users are "copy and paste" kind of guys, but you are having them paste file locations into a config file. I don't know your code, but if the config file is in python, you could add a line:
path_variable = input("Enter the path").replace("\\", "\\\\")
Python interprets \\ as \, which fixes your problem
This solves the problem of them copy-pasting into the file, and instead prompts them for the filepath.

Resources