Can't open and import files on Python - python-3.x

I just started learning Python this month with no prior coding knowledge. Before I could even get to practice coding, I was stuck with opening & importing files! To this end, I have no idea how to fix the problems as a newbie, so I will try to explain as best as I can.
1. Opening files.
Working directory is correct. The csv file was created with Geany on the Ubuntu operating system.
name=[]
age=[]
height=[]
with open(’/home/stephanie/chapter5exercise.csv’, encoding=’utf-8’,mode=’r’,newline=’’) as
csv file:
reader = csv.reader(csvfile, delimiter=’,’)
for row in reader:
name.append(row[0])
age.append(row[1])
height.append(row[2])
print("Done!")
**Error message:**
File "<ipython-input-3-f801fef0d65e>", line 5
with open(’/home/stephanie/chapter5exercise.csv’, encoding=’utf-8’,mode=’r’,newline=’’) as
^
SyntaxError: invalid character in identifier
2. Importing files
I downloaded a whatsapp chat text file for a coding exercise. It is stored in my Desktop environment. However, when I attempted to import it on Jupyter Notbook it didn't work.
I believe this is the problem, although I do not know how to work-around this:
the txt file's location as shown in my terminal:
/Users/Mac/Desktop
while the working directory as shown on Jupyter is:
/home/stephanie/Desktop
with open ("_chat.txt") as f:
data = f.readlines()
**error message:**
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-5-07cb5c381c47> in <module>
----> 1 with open ("_chat.txt") as f:
2 data = f.readlines()
FileNotFoundError: [Errno 2] No such file or directory: '_chat.txt'```
Any input or advice is greatly appreciated. Thanks very much in advance!

For the first error, try changing the apostrophes in the open line. For example, change ’/home/stephanie/chapter5exercise.csv’ to '/home/stephanie/chapter5exercise.csv'.
Apparently, the apostrophe (’) that you are using is not the correct one.
For the second error, try giving the entire path of the txt file.

Related

Spyder FileNotFoundError

I'm a newbie to programming. I want to switch my code from Jupyter to Spyder as I find the debugger better.
I'm trying to do something simple and open a file and I keep getting the "No such file or directory message". My text file is in the same directory as my .py file
file_palette = open(r"C:\Users\Myname.spyder-py3\palette.txt", 'r')

FileNotFoundError: No such file or directory in pygame [duplicate]

This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 2 years ago.
I am somewhat new to programming, I don't like it that much but as it is school work I have to do it, good thing I find it interesting.
Here is my code, note I'm using VS code (some things are in french but that shouldn't affect anything):
import pygame
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Space vaders")
fond = pygame.image.load (testingfield.png)
and I get:
Traceback (most recent call last):
File "c:/Users/faver/Desktop/Space_Invaders-NSI/space_invaders_1.py", line 11, in <module>
fond = pygame.image.load ('testingfield.png')
FileNotFoundError: No such file or directory.
the file is indeed in the folder, and if I put fond = pygame.image.load ((r'C:\Users\faver\Desktop\Space_Invaders-NSI\testingfield.png'))it works perfectly, the problem now is that it'd be hard to actually send it since the other person would lack the folders I place there.
I've also tried import os a = os.path.lexists("/Users/suyeon/Documents/pythonWorkspace/pygame_basic/character.png") print(a) and it returned false, so I'm pretty much confused, I'd appreciate help if possible ^^'
The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path).
One solution is to change the working directory:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
An alternative solution is to find the absolute path.
If the image is relative to the folder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the image filename. e.g.:
import pygame
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
# join the filepath and the filename
fondImgPath = os.path.join(sourceFileDir, 'testingfield.png')
fond = pygame.image.load(fondImgPath)

FileNotFoundError: [Errno 2]: Reading a file via jupyter

i started using Jupyter and fell into a problem. Whilst trying to read a file called 'vgsales' it gave an error:
FileNotFoundError: [Errno 2] File vgsales.csv does not exist: 'vgsales.csv'
I have put the 'vgsales' folder which has my csv file within it in my desktop with the Jupyter notebook.
Not sure where i went wrong, Please help!
Thanks
Code used:
import pandas as pd
df = pd.read_csv('vgsales.csv')
df
Though the notebook is on your desktop, you still can find out which folder it is in by simply right click on it and choose property. Then you can copy your csv file to the same folder
To list which files are in local folder when you are inside a notebook, use !ls, note that you need ! for the command to work

Error in using pyexiv2 metadata.read() method

I am trying to follow the tutorials in the pyexiv2 tutorials page
But due to some unknown reasons, it refuses to run, and I thought of seeking some advice from you.
`#this is my code
import pyexiv2
metadata = pyexiv2.ImageMetadata('test.png')
metadata.read()`
when I try to run this code in the terminal, with the python interpreter, in the folder which contains the image, 'test.png', following error is given.
`Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/pyexiv2/metadata.py", line 107,
in read
self.__image = self._instantiate_image(self.filename)
File "/usr/lib/python2.7/dist-packages/pyexiv2/metadata.py", line 74,
in
_instantiate_image
raise IOError(ENOENT, os.strerror(ENOENT), filename)
IOError: [Errno 2] No such file or directory: 'test.png'
`
This is my setup. I am running ubuntu 16.04LTS on virtual machine on a Mac book, with macOS sierra. Python version is 2.7.12.
I used this guide to install pyexiv2. when I inspect the /usr/local/lib folder, it shows that the libexiv2 is installed there.
What am I doing wrong here? and is there a better version of pyexiv2 to use?
I am fairly new to using python.:) and thanks in advance
This can be solved in two ways
1) Copy the file test.png in the same directory you have your python file with the code.
2) Provide a complete path. If, for example, you have test.png on your desktop, replace
metadata = pyexiv2.ImageMetadata('test.png')
with
metadata = pyexiv2.ImageMetadata('C:\\Users\\MYUSERPROFILENAME\\Desktop\\test.jpg')
where MYUSERPROFILENAME is your user profile. Hope this helps

Python idle not opening text file with open ()

being a few weeks old coder,I am unable to make python read my file despite the code and .txt file being in the same folder
highest_score=0
result_f = open("results.text")
for line in result_f:
if float (line)>highest_score:
highest_score = float(line)
result_f.close()
print("the highest score:")
print(highest_score)
and result is
Traceback (most recent call last):
File "C:\Python33\-mu.py", line 2, in <module>
result_f = open("results.text")
FileNotFoundError: [Errno 2] No such file or directory: 'results.text'
Please help
Basically you are trying to open the file result.text. The error returned is that Python Idle cannot find that file. I notice that you mentioned a .txt file but in your code you try to open a .text file.
So I would suggest you to check wheter your file extension is .txt or .text and, in case, correct.
If the error still persists, try to give the full path to the open command. For example:
result_f = open("/Users/Joe/Desktop/results.text")
Both Windows and Mac OS give, somewhere when right-clicking on the file, the full path (among other information).
I faced a similar issue, where I was trying to read a file in idle but it couldn't find the path. What worked for me:
Enter the full path of the file with the extension
Instead of the native path writing style in windows i.e. (D:\python\sample.txt)
use (D:/python/sample.txt)
It worked out for me in Windows 7, IDLE 3.6.4 and also works on Windows 8

Resources