Python 2.7: Calling a text file from various locations - python

So, I'm in the windows environment.
I created the text file with notepad.
I saved it in my documents.
I opened python's idle shell.
I used testFile = open("test.txt","a+")
Typed testFile.read()
Hit enter and the result was '' two single quotes?

You need to specify the full path to your text file if it is not in your current working directory:
testFile = open("c:/Users/yourusername/My Documents/text.txt")

testFile = open("test.txt", "rb")
testFile.read()

Related

python-opening a shortcut file in write mode gives me a return value 41

I was experimenting on files using python when I found out that opening a shortcut file in write mode returns 41, this is the code i used:
>>>with open('programs.lnk - Copy','w') as f:
f.write("C:\\Users\\DEVDHRITI\\AppData\\Local\\Programs")
>>>41
is this a bug or some specific id??
No. It's not a bug. It's is part of the API. Quoting from the documentation.
f.write(string) writes the contents of string to the file, returning the number of characters written.
>>> f.write('This is a test\n')
15
You actually try to open the file for writing here and not the target.
Link files is a windows specific feature. And to open the target you could do something like this:
import sys
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
print(shortcut.Targetpath)

Opening and Reading files in Python [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 3 months ago.
For some reason I am unable to open my .txt file within python.
I have the .py and .txt file within a folder. Both files are stored Workspace -> Folder(Crash Course) -> Folder(Lessons) -> Folder(Ch 10)-> both files within this Ch 10 Folder.
I am getting
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
With the code:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
This is less for the person that asked the question but more for people like myself that come here from Python Crash Course with the same question and don't get the answer they were looking for:
If, like me, you were running the code from your text editor (in my case VS Code), it's possible that the terminal window within the editor wasn't in the proper directory. I didn't realize myself, because I was thinking that because I opened the .py file from the correct working directory in the terminal that everything should work as planned. It wasn't until I realized that the terminal in the editor is a separate instance (thus making the present working directory home instead of my folder for PCC work) that I was able to get the program to run as intended.
In short, navigate to the proper directory in your editor's terminal instance and the program should run as intended.
Hope this helps!
image with terminal open on desktop and in text editor to show working directory difference
I used full path of the file along with r, which is for raw string. Worked for me.
example:
filename = **r**'C:\Python\CrashCourse\pi_digits.txt'
with open(filename) as file_object:
content = file_object.read()
print(content)
The path to the file is relative to where you run the python file from, not from where the python file is located.
Either run your code from the same directory as the files, or make the file path absolute, based on the python file's location.
import os
with open(os.path.join(os.path.dirname(__file__), 'pi_digits.txt')) as file_object:
contents = file_object.read()
print(contents)
Hope that helps
Try this:
with open('c:\\Workspace\\Crash Course\\Lessons\\Ch 10\\pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
You can try getting the full path to the file
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
pi_digits = os.path.join(dir_path, 'pi_digits.txt')
with open(pi_digits, r) as file_object:
print(file_object.read())
You might have to enable "Execute in file dir"
vscode setting

use Python to open a file in read mode

I am trying to open a file in read mode using Python. The error I am receiving suggest I am using the won filename or read mode. When I type the file path into my computer, it works. I tried to assign the input filename to a variable and then opening the variable in read mode. I also tried typing in the full path and opening the path in read mode. Both game me an error.
Code:
workingDirec = raw_input("What is the working directory?")
original_file = raw_input("The input filename is?")
def calculateZscore():
"Z score calc"
full_original = os.path.join(workingDirec,original_file)
print full_original
f = open ('C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data\NCSIDS_ObsExp.txt','r')
print f
My results:
Using full path output:
What is the working directory?C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data
The input filename is?NCSIDS_ObsExp.txt
C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data\NCSIDS_ObsExp.txt
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data\NCSIDS_ObsExp.txt'
Using variable output:
IOError: [Errno 2] No such file or directory: 'full_original'
On Windows your paths must be escaped because Windows uses backslashes \ to denote path separators.
Backslashes however are typically used as escape sequences and are used in Python as such as well! So you have to "escape" them like this:
f = open ('C:\\Users\\tpmorris\\ProgramingAndScripting\\Trial 2 Data\\Trial 2 Data\\NCSIDS_ObsExp.txt','r')
See:
Windows path in Python
Using Python on Windows
Firstly , on Windows, you must escape backslashes (double backslash) if you are going to use Windows path syntax, for the reasons pointed out by #James Mills answer.
Another option is to use forward slashes; Python will interpret these correctly in os.path.
You could use as your command line path input:
C:/Users/tpmorris/ProgramingAndScripting/Trial 2 Data/Trial 2 Data
Or add
/NCSIDS_ObsExp.txt
to the above if you were going to use a hardcoded path.
Also you should make some small changes to your code if you want to print the contents of your text file:
First, your file open should be done using a with statement. This will ensure the file object's built in __enter__ and __exit__ methods get called, in particular, if you forget to close the file when you are done after you've opened it.
See Understanding Python's with statement for more.
Second, if you want to print each line in your text file, don't try to print the file object. Rather loop through the lines and print them.
So your code for accepting command line input should be:
import os
workingDirec = raw_input("What is the working directory?")
original_file = raw_input("The input filename is?")
full_original = os.path.join(workingDirec,original_file)
print full_original
with open(full_original,'r') as f:
for line in f:
print line
f.close()
I removed the def of a function to do something else in the midst of your file read code. That def should go elsewhere.

How to write a whole string to a file in Python and where does the file go?

I am doing an assignment on text formatting and alignment (text wrapping) and I need to write my formatted string to new file. But once I have written to the file (or think I've written) where does that file go? Does it actually create a file on my desktop or am I being stupid?
This is my code:
txtFile = open("Output.txt", "w")
txtFile.write(string)
txtFile.close()
return txtFile
Cheers,
JT
The text is written to a file called "Output.txt" in your working directory (which is usually the directory from which the script has been executed).
To display the working directory, you can use:
>>> import os
>>> os.getcwd()
'/home/adam'
When you open a file without specifying a file path, the file will be created in the python scripts working directory.
Usually that is the location of your script but there are times when it may be a different place.
The os module in python will provide functions for checking and changing the working directory within python itself.
most notably:
os.chdir(path)
os.fchdir(fd)
os.getcwd()
It will create a new file called "Output.txt" in the same directory that you executed your script from. It may mean that the file can't be written to, if you're in a directory that doesn't have the appropriate permissions for your user.

Python Command Line Arguments (Windows)

I am running 32-bit Windows 7 and Python 2.7.
I am trying to write a command line Python script that can run from CMD. I am trying to assign a value to sys.argv[1]. The aim of my script is to calculate the MD5 hash value of a file. This file will be inputted when the script is invoked in the command line and so, sys.argv[1] should represent the file to be hashed.
Here's my code below:
import sys
import hashlib
filename = sys.argv[1]
def md5Checksum(filePath):
fh = open(filePath, 'rb')
m = hashlib.md5()
while True:
data = fh.read(8192)
if not data:
break
m.update(data)
return m.hexdigest()
# print len(sys.argv)
print 'The MD5 checksum of text.txt is', md5Checksum(filename)
Whenver I run this script, I receive an error:
filename = sys.argv[1]
IndexError: list index out of range
To call my script, I have been writing "script.py test.txt" for example. Both the script and the source file are in the same directory. I have tested len(sys.argv) and it only comes back as containing one value, that being the python script name.
Any suggestions? I can only assume it is how I am invoking the code through CMD
You should check that in your registry the way you have associated the files is correct, for example:
[HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command]
#="\"C:\\Python27\\python.exe\" \"%1\" %*"
The problem is in the registry. Calling python script.py test.txt works, but this is not the solution. Specially if you decide to add the script to your PATH and want to use it inside other directories as well.
Open RegEdit and navigate to HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command. Right click on name (Default) and Modify. Enter:
"C:\Python27\python.exe" "%1" %*
Click OK, restart your CMD and try again.
try to run the script using python script.py test.txt, you might have a broken association of the interpreter with the .py extention.
Did you try sys.argv[0]? If len(sys.argv) = 0 then sys.argv[1] would try to access the second and nonexistent item

Categories

Resources