I wanted to run this piece of code to see if anything outputs. I ran pieces of code like this in my work windows VM and it works perfectly. I switch over to my local Windows computer and I can't understand for the life of me why this can't output anything if I'm in a folder on my desktop.
I'm using Python 3.9.6. I thought it was a root logging problem here because that is what I was testing at first. But then realized I can't output anything. I'm using IntelliJ IDEA Community Edition 2022.3.2. Then tested on sublime and nothing worked. I am getting no errors. My working directory is also correctly set to the directory I'm in. Giving the full path does not work either.
I am using Windows 10.
import logging
import pandas as pd
# Cant create logger
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
# Cant Create CSV
df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
'mask': ['red', 'purple'],
'weapon': ['sai', 'bo staff']})
df.to_csv("csv_file.csv",index=False)
# Can't output empty text file.
with open('sample.csv', 'w') as creating_new_csv_file:
pass
Related
I am trying to do a simple csv read for my code and it has worked up until I tried tonight for Mac. Currently on 10.15.3, Catalina. This is my code:
df = pd.read_table('/Users/nicholasmori/Desktop/FINAL.csv', delimiter=',')
And the error it gave me was:
OSError: Initializing from file failed.
Ive tried multiple different options to read this csv, including
pd.read.csv(open( ) )
csv.reader( )
pd.read_csv()
with open ( ) as csvfile:
But all these give similar errors. I am sure theres a simple answer, but I haven't been able to find it. Ive tried the
sudo chown username:group filename
command on terminal, and allowed terminal access through my privacy/firewall settings. My file also has Read & Write permissions for "everyone," unless I'm viewing that wrong. Does anyone have a solution for me?
I had the same error, what I did was upload the file to jupyter from my Mac (same root of the python program) and:
import pandas as pd
path_file = "FileName.csv"
data = pd.read_csv(path_file)
Hope works!
When did you upgrade from macOS Catalina (10.15.x) from a previous version (10.14)? OS-level access rights are a bit different.
Also, you can try this, to verify that the file (and path, if provided) are correct:
from pathlib import Path
file_name = 'test.npy'
Path(file_name).is_file() # returns True or False
print(Path.cwd()) # prints current working directory
I am learning Python through 'Automate the Boring Stuff With Python' First Edition. In chapter 12, pg 267, we are supposed to open a file called example.xlsx.
The author's code reads:
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
type(wb)
However, when I try to open this file, I get the following error (this is the last line of the error):
FileNotFoundError: [Errno 2] No such file or directory: 'example.xlsx'
I know this file exists, because I downloaded it myself and am looking at it right now.
I have tried moving it to the current location in which Python 3.8 is, I have tried saving it with my Automate the Boring Stuff files that I've been working on the desktop, and I have tried saving it in every conceivable location on my machine, but I continue getting this same message.
I have imported openpyxl without error, but when I enter the line
wb = openpyxl.load_workbook('example.xlsx')
I have entered the entire pathway for the example.xlsx in the parenthesis, and I continue to get the same error.
What am I doing wrong? How am I supposed to open an Excel workbook?
I still don't understand how I am doing wrong, but this one is incredibly infuriating, and I feel incredibly stupid, because it must be something simple.
Any insight/help is greatly appreciated.
Your error is unambigous — your file in a supposed directory don't exist. Believe me.
For Python is irrelevant, whether you see it. Python itself must see it.
Specify the full path, using forward slashes, for example:
wb = openpyxl.load_workbook('C:/users/John/example.xlsx')
Or find out your real current (working) directory — and not the one supposed by you — with commands
import os
print(os.getcwd())
then move your example.xlsx to it, and then use only the name of your file
wb = openpyxl.load_workbook('example.xlsx')
You may also verify its existence with commands — use copy/paste from your code to avoid typos in the file name / path
import os.path
print(os.path.exists('example.xlsx')) # True, if Python sees it
or
import os.path
print(os.path.exists('C:/users/John/example.xlsx')) # True, if exists
to be sure that I'm right, i.e. that the error is not in the function openpyxl.load_workbook() itself, but in its parameter (the path to the file) provided by you.
I notice that the extension of the example file is not the same as described in the book, is example.csv. I was facing the same frustration as you
I'm automating my current reports and need help getting up and running.
I have a PS script that first fixes a csv file and then calls a python script. Within the python script I am importing modules that 'cannot be found' when the PS script runs.
I have tried importing the modules separately(but within the powershell script) to no avail. I have been trying to run from PyCharms using a powershell plugin. Even though I have tried running it in Powershell IDE and it produces the same error.
This is where it chokes. If I need to delve further please let me know and I will remove the sensitive information in the code and post it.
#POWERSHELL CODE
#start excel
$Excel = New-Object -Com Excel.Application
#make it visible (just to check what is happening)
$Excel.Visible = $true
#open file
$FilePath = 'file path here'
$Workbook = $Excel.Workbooks.Open($FilePath)
$Worksheets = $Workbooks.worksheets
#change column format type for DateTime issue in logs
$workbook.ActiveSheet.Columns.Item("X").NumberFormat = "yyyy-mm-dd hh:mm:ss"
$Output.ExitCode
#save doc and close excel
$ext=".csv"
$path="file here"
$workbook.SaveAs($path)
$workbook.Close
$Excel.DisplayAlerts = 'False'
$Excel.Quit()
$Output.ExitCode
python "file here" #calling python script here
$Output.ExitCode
#PYTHON CODE
import MySQLConnection2 as mc
import RedshiftConnection2 as rc
from Data_download2 import dict_to_csv
from os.path import join, basename
import datetime
import csv
import pandas as pd
import numpy as np
import sys
The python code generates several csv files that are needed for this report. Once I get past this choke I will need to call another python script and then alter the csv files.
Error Message > 'Import-Module : The specified module 'SQLalchemy' was not loaded because no valid module file was found in any module
directory.'
You cannot use Import-Module on python scripts and python modules.
This code:
workbook.save(outputf)
system('open ' + outputf)
generates this error when run on my mac:
sh: /Users/tylerjw/Desktop/jim_data/August2013_report.xlsx: Permission denied
The file was created with openpyxl. I have not been able to reproduce the error outside of my application is a tkinter application that is writing a considerable amount of data to that file.
When I run similar code in windows it doesn't error, it opens excel with the file. The only difference is the absence of the open command.
What could case this error?
On my system (mac 10.6.8, python2.7.5, gcc 4.2.1) the following code works fine:
from openpyxl import Workbook
from os import system
wb = Workbook()
outputf = 'test.xlsx'
wb.save(outputf)
# see below *
system('open ' + outputf)
(see comments: I lost the bet. The error was somewhere else in the code and has nothing to do with system('open ' + whatever))
I bet there is something wrong with permissions in your new file on your system. Maybe you add
(docu)
st = os.stat(outputf)
os.chmod(outputf, st.st_mode | stat.stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
(with input from other link)
in the code instead of my commentary ('# see below *') Then it should be possible to open it by everyone and everything...
If it works, this is a workaround. There is a difference between our system and I do not know what difference. If not, well, I did not test it on my system (because I did not have a problem with the code), write a comment and I might play with the settings or maybe someone else has an idea.
Btw.: In a terminal in your folder: What output gives 'ls -l excelfilename' after execution of the python code? What programming environment do you use? I start the program via 'python2.7 pythonscript.py' in the terminal.
I have a rather simple program that writes HTML code ready for use.
It works fine, except that if one were to run the program from the Python command line, as is the default, the HTML file that is created is created where python.exe is, not where the program I wrote is. And that's a problem.
Do you know a way of getting the .write() function to write a file to a specific location on the disc (e.g. C:\Users\User\Desktop)?
Extra cool-points if you know how to open a file browser window.
The first problem is probably that you are not including the full path when you open the file for writing. For details on opening a web browser, read this fine manual.
import os
target_dir = r"C:\full\path\to\where\you\want\it"
fullname = os.path.join(target_dir,filename)
with open(fullname,"w") as f:
f.write("<html>....</html>")
import webbrowser
url = "file://"+fullname.replace("\\","/")
webbrowser.open(url,True,True)
BTW: the code is the same in python 2.6.
I'll admit I don't know Python 3, so I may be wrong, but in Python 2, you can just check the __file__ variable in your module to get the name of the file it was loaded from. Just create your file in that same directory (preferably using os.path.dirname and os.path.join to remain platform-independent).