new to python. Just started a rigging class that is starting to get into scripting. I found a practice for python and I am having trouble with an error.
import maya.cmds as cmds
stockPath = "C:\Users\Dryan\Desktop\table.csv"
f = open(stockPath)
data = f.read()
f.close()
print data
This is the error I get.
> # Error: line 1: IOError: file <maya console> line 4: 22 #
Again this is just a practice to get the file of number to print in the script editor. Thank you for any help.
The likeliest problem is that you're using backslashes in your file name, so they get interpreted as control characters. The IO error is because the filename is mangled.
try
stockPath = "C:\\Users\\Dryan\\Desktop\\table.csv" # double slashes to get single slashes in the string
or
stockPath = "C:/Users/Dryan/Desktop/table.csv" # it's more python-y to always use right slashes.
As joojaa said, try to avoid using backslashes when you can. I try to always convert any incoming path to a forward slashes version, and just before outputting it I normalize it using os.path.normpath.
clean_path = any_path_i_have_to_deal_with.replace("\\", "/")
# do stuff with it
# (concat, XML save, assign to a node attribute...)
print os.path.normpath(clean_path) # back to the OS version
Related
I have a simple JSON file that I was supposed to use as a configuration file, it contains the default directories for whoever is running the script using their MacBooks:
{
"main_sheet_path": "/Users/jammer/Documents/Studios/CAT/000-WeeklyReports/2020/",
"reference_sheet_path": "/Users/jammer/Documents/DownloadedFiles/"
}
I read the JSON file and obtain the values using this code:
with open('reportconfig.json','r') as j:
config_data = json.load(j)
main_sheet_path = str(config_data.get('main_sheet_path'))
reference_sheet_path = str(config_data.get('reference_sheet_path'))
I use the path to check for a source file's existence before doing anything with it:
source_file = 'source.xlsx'
source_file = main_sheet_path + filename
if not os.path.isfile(source_file) :
print ('ERROR: Source file \'' + source_file + '\' NOT FOUND!')
return
Note that the filename is inputted as a parameter when the script is run (there are multiple files, the script has to know which one to target).
The file is there for sure but the script never seems to "see" it so I get that "ERROR" that I printed in the above code. Why do I think there are invisible characters? Because when I copy and paste from what was printed in the "error" notice above into the terminal, the last few characters of the file name always gets substituted by some invisible characters and hitting backspace erases characters where the cursor isn't supposed to be.
How do I know for sure that the file is there and that my problem is with reading the JSON file and not in the Directory names or anywhere else in the code? Because I finally gave up on using a JSON config file and went with a configuration file like this instead:
#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
file_paths = { "main_sheet_path": "/Users/jammer/Documents/Studios/CAT/000-WeeklyReports/2020/",
"reference_sheet_path": "/Users/jammer/Documents/DownloadedFiles/"
}
I then just import the file and obtain the values like this:
import reportconfig as cfg
main_sheet_path = cfg.file_paths['main_sheet_path']
reference_sheet_path = cfg.file_paths['reference_sheet_path']
...
This workaround works perfectly — I don't get the "error" that the file isn't there when it is and the rest of the script is executed as expected. When the file isn't there, I get the proper "error" I expect and copying-and-pasting the full path and filename from the "error message" gives me the complete file name and hitting the backspace erases the right characters (no funny behavior, no invisible characters).
But could anyone please tell me how read the JSON file properly without getting those pesky invisible characters? I've spent hours trying to figure it out including searching seemingly related questions in stackoverflow but couldn't find the answer. TIA!
I think there is just a typo error in this code:
source_file = 'source.xlsx'
source_file = main_sheet_path + filename
Maybe filename is set to some other file which is not present hence it is giving you error.
Try to set filename='source.xlsx'
Maybe it will help
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.
I am trying to write code that takes 2 numbers in a text file and then divides them, showing the answer as a top heavy fraction. I have gotten the fractions part to work when I am inputting my own values in the program, but i cannot get the program to recognise the text file. I have tried putting them in the same directory and putting the full system path of the file, but nothing so far has worked. right now I am just trying to get the contents of the file to print.
with open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w') as f:
for line in f:
for word in line.split():
print(word)
I will then assign the 2 values to x and y, but I get this error:
Traceback (most recent call last):
File "C:\Python34\divider.py", line 2, in <module>
open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w')
OSError: [Errno 22] Invalid argument:'C:\\ProgramData\\Microsoft\\Windows\\Startmenu\\Programs\\Python 3.4\topheavy.txt'
open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w')
OSError: [Errno 22] Invalid argument:'C:\\ProgramData\\Microsoft\\Windows\\Startmenu\\Programs\\Python 3.4\topheavy.txt'
Two things:
When working with paths that contain backslashes, you either need to use two backslashes, or use the r'' form to prevent interpreting of escape sequences. For example, 'C:\\Program Files\\...' or r'C:\Program Files\...'.
Your error shows this: \\Startmenu\\. It appears that a space is missing between "Start" and "menu", despite the fact that the open line seems to have the right path.
Note: that the \topheavy.txt in your path is probably getting converted to <tab>opheavy.txt too. That's why there aren't two backslashes in front of it in the traceback.
You are using a "\" separator which is probably getting escaped somewhere (like that \t near the end. That's the Windows path separator, but also used as a string escape.
You can double up the "\" as "\". Easiest however is to prepend an r at the beginning to ignore .
r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt"
Skip the recommendation to use / instead, you are not on Unix and there is no reason Python can't accommodate Windows, as long as you remember to take care about "\" also being an escape. Using r' at start also allows you to copy/paste from the string into another program or vice-versa.
also, it wouldn't hurt to test in c:\temp or similar to avoid issues where you may have mistyped your path.
Last, but not least, you need to open in "r" read mode, as previously mentioned.
You should add one more "/" in the last "/" of path for example:
open('C:\Python34\book.csv') to open('C:\Python34\\\book.csv')
Reference
I had this same error appear when trying to read a large file in Python 3.5.4. To solve it, instead of reading the whole file into memory with .read(), I read each line one by one:
with open('big.txt') as f:
for i in f:
print(i)
Just as is written on the Python Documentation, the IOError Exception occurs:
Raised when an I/O operation (such as a print statement, the built-in
open() function or a method of a file object) fails for an I/O-related
reason, e.g., “file not found” or “disk full”.
Open with "r" (read) instead of "w" (write)
And startmenu in these two lines are different?? Try using a forward instead of a back slash. Python will convert the forward slash to the appropriate delimiter for the OS it is running on
open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w')
OSError: [Errno 22] Invalid argument:'C:\ProgramData\Microsoft\Windows\Startmenu\Programs\Python 3.4\topheavy.txt'
Replace every \ with \\ in file path
My issue, rather arbitrary, was I was writing a file using open(filename, "w").write(...), where filename is an invalid pathname or includes unexpected slashes.
For example, converting a datetime.datetime.today() into a datestring with slashes or colons (Windows) and writing to non-existing directories will result in this error.
Change:
open("../backup/2021/08/03 15:02:61.json", "w").write(data)
To:
open("../backup/2021-08-03 15-02-61.json", "w").write(backup)
As an example.
I am new to python trying to open a file in python using:
phys = "C:\\parsework\\glckpysdata.txt"
print phys
d = open(phys)
When I run I get:
C:\parsework\glckpysdata.txt
Traceback (most recent call last):
File "C:\py\boxtest2.py", line 28, in <module>
d = open(phys)
IOError: [Errno 2] No such file or directory: 'C:\\parsework\\glckpysdata.txt'
I feel like I've tried everything (phys = r"C:\parsework\glckpysdata.txt", direct entry into the open command with double and single quotes/backslashes ect...) nothing seems to prevent it from reading the path with the double backslashes.
The most frustrating thing about this I have the exact same syntax in the same script and it works perfectly there:
thisguy = "C:\\parsework\\glckout\\"
thisguy += nam
g = open(thisguy)
is in the same script and works fine. Can someone tell me what's going on?
Your problem is not the double backslash in the path -- this is just an artifact from displaying the representation of the string in the error message. The actual string does not contain double backslashes.
Your problem simply is that C:\parsework\glckpysdata.txt does not exist, just as the error message says.
By the way, to avoid this kind of issue, simply use forward slashes in paths:
phys = "C:/parsework/glckpysdata.txt"
Either of the following is correct:
phys = "C:\\parsework\\glckpysdata.txt"
or
phys = r"C:\parsework\glckpysdata.txt"
The exception means that the file doesn't exist, or you don't have permissions to access it. Double-check the path and the filename (at a guess, are you missing an h in glckpysdata.txt?)
The double backslashes in the exception message are simply how embedded backslashes are displayed; every \\ corresponds to a single backslash in the string.
Ok, so I am trying to write a Python script for XCHAT that will allow me to type "/hookcommand filename" and then will print that file line by line into my irc buffer.
EDIT: Here is what I have now
__module_name__ = "scroll.py"
__module_version__ = "1.0"
__module_description__ = "script to scroll contents of txt file on irc"
import xchat, random, os, glob, string
def gg(ascii):
ascii = glob.glob("F:\irc\as\*.txt")
for textfile in ascii:
f = open(textfile, 'r')
def gg_cb(word, word_eol, userdata):
ascii = gg(word[0])
xchat.command("msg %s %s"%(xchat.get_info('channel'), ascii))
return xchat.EAT_ALL
xchat.hook_command("gg", gg_cb, help="/gg filename to use")
Well, your first problem is that you're referring to a variable ascii before you define it:
ascii = gg(ascii)
Try making that:
ascii = gg(word[0])
Next, you're opening each file returned by glob... only to do absolutely nothing with them. I'm not going to give you the code for this: please try to work out what it's doing or not doing for yourself. One tip: the xchat interface is an extra complication. Try to get it working in plain Python first, then connect it to xchat.
There may well be other problems - I don't know the xchat api.
When you say "not working", try to specify exactly how it's not working. Is there an error message? Does it do the wrong thing? What have you tried?