Transferring data from python to excel

import os
os.getcwd()
os.chdir(“C:\Users\Admin”)
os.getcwd()
df = pd.read_csv(‘Muhammad123’)
FileNotFoundError Traceback (most recent call last)

I want to transfer data from python to excel but after writing the code the error is appearing that file not found. Can you suggest what is the error?

import os
os.getcwd()
os.chdir(“C:\Users\Admin”)
os.getcwd()
df = pd.read_csv(‘Muhammad123’)
FileNotFoundError Traceback (most recent call last)

Please always include the complete traceback. It will normally at least
indicate which line of code had the error.

I want to transfer data from python to excel but after writing the code
the error is appearing that file not found. Can you suggest what is the
error?

Well it seems likely that either the path “C:\Users\Admin” does not
exist, or that your CSV file is not called ‘Muhammad123’. Maybe
‘Muhammad123.csv’ ?

But a traceback will be more informative.

Cheers,
Cameron Simpson cs@cskk.id.au

Ali123 wrote:

“after writing the code the error is appearing that file not found. Can
you suggest what is the error?”

The file name is wrong. Perhaps you spelled the file name wrong, or
you forgot the file extension. Did you forget to put “.csv” in the file
name? Or “.xls”?

Or you are in the wrong directory.

Or the file has been deleted. Did you accidently delete the file?

import os
os.getcwd()
os.chdir(‘Desktop\12345646’)
os.getcwd()
df = pd.read_csv(‘12345646.csv’)

Now, I have changed the path and have given it more simple path via Desktop but it still shows the error in this way

FileNotFoundError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7328/1026938101.py in
1 import os
2 os.getcwd()
----> 3 os.chdir(‘Desktop\12345646’)
4 os.getcwd()
5 df = pd.read_csv(‘12345646.csv’)
FileNotFoundError: [WinError 2] The system cannot find the file specified: ‘DesktopS45646’

You shouldn’t use backslashes for pathnames. Use forward slashes.

Backslashes are used for string escapes. Look at the error message:

FileNotFoundError: [WinError 2] The system cannot find 
the file specified: 'DesktopS45646'

Read the error message carefully. What is the filename?

Now run this code and see what it does: print('\123')

Then read this:

https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

especially the section about escape sequences.

You can:

Double up your backslashes: ‘Desktop\12345646’

Or use a forward slash: ‘Desktop/12345646’

In addition to Steven’s comments and echoing his suggestion to always use /, not \ for paths (not only is it preferred by Python, in almost all contexts its equally allowed as \ in Windows paths as well), also keep in mind that os.chdir(‘Desktop/12345646’) uses a relative path, so it assumes you are in your user home directory (C:/Users/Admin, possibly). If you are anywhere else, it won’t work—including if you’ve already successfully run the script at least once past that line in the same environment.

You could get around this by using an absolute path for os.chdir (C:/Users/Admin/Desktop/12345646), but it still changes the state of your working environment for all subsequent code, and it means that if you move anything around or share your code with others, it won’t work. You could save the CWD and change it back, but that won’t work if you run into an error between dir changes (unless you make your own context manager, which is way overkill at this point).

As such, I’d suggest simply making a project directory for your work somewhere, putting your code and your data somewhere inside of that, and running your script with that as your working directory and specifying the relative path from there to your CSV file, with no os.chdir necessary.

Unfortunately, it is showing the same error even though I have changed backslash to forward slash

Taceback (most recent call last):
File “C:/Users/Admin/Muhammad123.py”, line 3, in
os.chdir(‘Desktop/Muhammad123’)
FileNotFoundError: [WinError 2] The system cannot find the file specified: ‘Desktop/Muhammad123’

Thanks, can you express what you want to say through a template of some type?

Without seeing the full layout of the filesystem, it is impossible to know exactly what is going on, but as the error clearly states, the directory Desktop/Muhammad123 relative to wherever you are now (which you can see by print() ing your os.getcwd() calls does not exist. As I mentioned above, if you MUST use chdir, you need to either use a full absolute path when you are running os.chdir() (I provide the full command above) and make sure that you’ve created the 12345646, Muhammad123 or whatever you choose to call it directory.

However, I describe a better approach above, which you should use instead unless you are absolutely required to use chdir. Breaking that down for you step by step:

  1. Create a new directory (which I’ll call your project directory) for your project somewhere convenient (Desktop, Documents, wherever you want).
  2. Move your Python script and your CSV inside your new project directory.
  3. In your code, remove the os.chdir calls and ensure the path to your CSV inside pd.read_csv() is relative to your project directory (in this case, just TheCSVsFileName.csv)
  4. From your editor, IDE or terminal/command prompt, change your working directory to your project directory and run your script from there

This helps keep things organized and consistent, while ensuring everything will still work if you move your project directory somewhere else, or even to another machine.

I’m not sure exactly what you mean by “a template”, sorry, but I provided step by step instructions above that you should read and follow, as well as ensuring you understand the explanation for what is being done and why (or otherwise, you’ll likely to run into this again in the future without understanding what is really going on).

When I make the code in this way, then the software reads it but still the problem occurs and that is that the code gives result not in desired form. It simply shows the range and other factors.
import pandas as pd
import openpyxl as xls
df = pd.read_csv(‘Desktop/Muhammad123.py’)
df
excel_file = pd.ExcelWriter(‘jaipur.xlsx’)
df.to_excel(excel_file)
excel_file.save()
The output on excel is in this form

Perhaps it was a quirk of language, but just to be clear, its not “the problem”, its “a problem”. If you change something get a different error message or different behavior, both of which were the case here, its usually a different problem and should be treated as such.

The proximate issue here is quite clear. Look at this line in your code

 df = pd.read_csv(‘Desktop/Muhammad123.py’)

In particular, pay close attention to the file extension (the part after the dot). And what do you see in your “data table”? Is it the contents of the CSV file, or is it the contents of a different file? In general, if you’re not getting the content you expect, your first recourse should be to look at the file path and contents of the file, and see if it matches what is output by your code.

Again, to reduce the risk of this confusion and make it easier to move your project around, I highly recommend following the steps above to put both your code and your data in one project directory (say, named PythonExcel or something else clear and appropriate for your project), set all your paths relative to that directory, and then ensure your working directory in Spyder, Jupyter, or your command prompt is set to that PythonExcel directory. This is generally what is done in scientific computing and keeps things simpler, more organized and easy to follow vs. spreading everything around.

EDIT: As a tip, use triple backticks above and below your code, so it will display properly and be copy/pastable. In particular, this preserves indentation, which is syntactically and semantically very important in Python, as well as things like fancy quotes and formatting.

Like this:

```python

YOUR CODE HERE

```