What is wrong with this code to open a file? - python

I tried this code to open a file in Python:
f = open("/Desktop/temp/myfile.txt","file1")
It didn't work. I think this is because I didn't specify the right path. How can I fix the problem?

That doesn't work as you've got the wrong syntax for open.
At the interpreter prompt try this:
>>> help(open)
Help on built-in function open in module __builtin__:
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object.
So the second argument is the open mode. A quick check of the documentation and we try this instead:
f = open("/Desktop/temp/myfile.txt","r")

Edit: Oh and yes, your second argument is wrong. Didn't even notice that :)
Python looks where you tell it to for file opening. If you open up the interpreter in /home/malcmcmul then that will be the active directory.
If you specify a path, that's where it looks. Are you sure /Desktop/temp is a valid path? I don't know of many setups where /Desktop is a root folder like that.
Some examples:
If I have a file: /home/bartek/file1.txt
And I type python to get my interpreter within the directory /home/bartek/
This will work and fetch file1.txt ok: f = open("file1.txt", "r")
This will not work: f = open("some_other_file.txt", "r") as that file is in another directory of some sort.
This will work as long as I specify the correct path: f = open("/home/media/a_real_file.txt", "r")

To begin with, the second argument is the permissions bit: "r" for read, "w" for write, "a" for append. "file1" shouldn't be there.

Try:
f = open('Desktop/temp/myfile.txt', 'r')
This will open file relatively to current directory. You can use '/Desktop/temp/myfile.txt' if you want to open file using absolute path. Second parameter to open function is mode (don't know what file1 should mean in your example).
And regarding the question - Python follows OS scheme - looks in current directory, and if looking for modules, looks in sys.path afterwards. And if you want to open file from some subdirectory use os.path.join, like:
import os
f = open(os.path.join('Desktop', 'temp', 'myfile.txt'), 'r')
Then you're safe from the mess with '/' and '\'.
And see docs for built-in open function for more information about the way to use open function.

Just enter your file name and there is your data.....what it does?---->If path exists checks it is a file or not and then opens and read
import os
fn=input("enter a filename: ")
if os.path.exists(fn):
if os.path.isfile(fn):
with open(fn,"r") as x:
data=x.read()
print(data)
else:
print(fn,"is not a file: ")
else:
print(fn,"file doesnt exist ")

This:
import os
os.path
should tell you where python looks first. Of course, if you specify absolute paths (as you have), then this should not matter.
Also, as everyone else has said, your second argument in open is wrong. To find the proper way of doing it, try this code:
help(open)

A minor potential issue that the original post does not have but, also make sure the file name argument uses '/' and not '\'. This tripped me up as the file inspector used the incorrect '/' in its location.
'C:\Users\20\Documents\Projects\Python\test.csv' = Does not work
'C:/Users/20/Documents/Projects/Python/test.csv' = Works just fine

from pathlib import Path
import os
desired_directory = Path('C:/')
desired_directory = desired_directory / 'subfolder'
os.chdir(desired_directory)
That will force Python to look at the directory in the path you specify. It works well when using `subprocess.Popen' to use binary files, as in this snippet:
from subprocess import Popen
from shutil import which
instance_of_Popen = Popen(which('name_of_executable'))
print(instance_of_Popen.args)

Related

Confusing problem >> FileNotFoundError: [Errno 2] No such file or directory:

This problem puzzled me.
Maybe the problem is in the code, I hope you take a look
with open(training_images_labels_path,'r') as file:
lines = file.readlines()
He says that the file does not exist
FileNotFoundError: [Errno 2] No such file or directory: '\\Desktop\\project\\data\\generated\\training_images_labels.txt'
Though the file exists
I need solutions
If it says that the file does not exist though the file exists, it means the path has been not given properly. Try giving the path correctly.
Method 1:
Giving correct path 'C:\\Users\\Public\\Desktop\\project\\data\\generated\\training_images_labels.txt' or
'C:\\Users\\<insert your username>\\Desktop\\project\\data\\generated\\training_images_labels.txt' is your path if I guess correctly
Method 2:
Using os module ( Recommended )
mydir = 'C:/Users/Public/Desktop/project/data/generated'
myfile = 'training_images_labels.txt'
training_images_labels_path = os.path.join(mydir, myfile)
with open(training_images_labels_path,'r') as file:
lines = file.readlines()
Method 3:
You can also try changing the working directory to the location where your data is present. ie Desktop>project>data>generated here and open the file with file name. ie
with open('training_images_labels.txt','r') as file:
lines = file.readlines()
I had the same problem with importing an excel file, which of course exists in the same directory with my .py file. The chosen solution above did not help me, and actually I didn't understand those three methods, as I am working on mac OS.
This method worked for me: in Spyder, I usually run the file by pressing the keys "Shift + Enter", which in this case made the problem. So, my solution was, to press on the "Run file" button (or the fn+F5 key) instead.
Maybe someone wants to explain the difference.
Looks like its a windows path you are working and i believe path really thrown in the error is wrong when compared to the actual where the txt file resides.. just cross check once, if that's the case try to pass the correct path in to the variable "training_images_labels_path"
Can you tell how you created this path.Some advise.
use path separator library to generate path to avoid this error.
training_images_labels_path
further try to navigate parent directory using python and print pth.may be some new line or linux/windwos convereted path or other special character in path. navigating parent directory and listing will solve
if still not solve try to navigatep parent-parent dir and print path
try hard
Watch your path if its correct or not. I had the same problem and it turned out i didnt had the good path set

Add to ~/.zshrc file with python

I'm trying to write a cli that will take a users path that they input into the command line, then add this path to the correct path file depending on their shell - in this case zsh. I have tried using:
shell = str(subprocess.check_output("echo $SHELL", shell=True))
click.echo("Enter the path you would like to add:")
path = input()
if 'zsh' in shell:
with open(".zshrc", 'w') as zsh:
zsh.write(f'export PATH="$PATH:{path}"')
This throws no errors but doesn't seem to add to the actual ~./zshrc file.
Is there a better way to append to the file without manually opening the file and typing it in?
New to this so sorry if it's a stupid question...
Open the file in append mode. Your code also assumes that the current working directory is the user's home directory, which is not a good assumption to make.
from pathlib import Path
import os
if 'zsh' in os.environ.get("SHELL", ""):
with open(Path.home() / ".zshrc", 'a') as f:
f.write(f'export PATH={path}:$PATH')
with (Path.home() / ".zshrc').open("a") as f: would work as well.
Note that .zprofile would be the preferred location for updating an envirornent variable like PATH, rather than .zshrc.
Solved! Just want to put the answer here if anyone comes across the same problem.
Instead of trying to open the file with
with open(".zshrc", 'w') as zsh:
zsh.write(f'export PATH="$PATH:{path}"')
you can just do
subprocess.call(f"echo 'export PATH=$PATH:{path}' >> ~/.zshrc", shell=True)
If anybody has a way of removing from ~/.zshrc with python that would be very helpful...

How to change where the file being created when using .open("fileName", "w+") function in Python(VS code environment)?

How can I change where the textfile.txt should be created in VS IDE?
This is the whole structure of the project
Learning Python
>.sfdx
>.vscode
>Debug
>Exercise File
The current file I am editing on is somewhere in Exercise File, however when the textile.txt is created by Python, it is located in the folder of Learning Python.
Learning Python
>.sfdx
>.vscode
>Debug
>Exercise File
>textfile.txt
Thank you for reading my question, hope it is clear enough!
You can use the own python to do that, using getcwd and chdir methods from os. The getcwd return the current working directory and chdir is used to change the working directory.
import os
current_path = os.getcwd()
print(current_path)
new_path = "/your/path"
os.chdir(new_path)
print(new_path)
Just specify the full path of the file in the open function.
f = open(r"C:\Users\deepstop\Documents\textfile.txt", "w+")
The r in front of the string is important. It means "raw" and prevents the backslashes in the string from being interpreted as escape characters.

Python/CSV - File not found error

A basic question but I've got a file, say file.csv, in the directory, C:/Users/User/Desktop/Other/DataAnalysis/CurrentData/file.csv, and so I've written,
df = pd.read_csv("C:/Users/User/Desktop/Other/DataAnalysis/CurrentData/file.csv")
and I get an error -
> FileNotFoundError: File
> b'C:/Users/User/Desktop/Other/DataAnalysis/CurrentData/file.csv' does not exist
I've tried
df = pd.read_csv("file.csv")
As the file.csv is in the exact same folder as my python script, and I still get the same error. I'm not sure what I've done wrong. I've checked the python API and I've tried reversing the brackets (so using \\ instead of /), and still doesn't work.
Thank you.
Try something like:
with open(my_file, 'r') as f_in:
for line in f_in:
print(line)
That way you can check if Python can open the file at all.
Check the extension it might be .csv.txt or .csv.csv
Window users
use forward slash:
import pandas as pd
df_swing = pd.read_csv('D:/anaconda/envs/data/EDA/2008_all_states.csv')
Example shown above is of absolute path. It's complete path from the base of your file system to the file that you want to load, e.g. c:/Documents/Shane/data/test_file.csv. Absolute paths will start with a drive specifier (c:/ or d:/ in Windows, or ‘/’ in Mac or Linux)

How to create a file in a folder

How can i create a .pck file in a folder in Python?
The name of the folder is example
I tried:
file = open("\example\file.pck","wb")
But it says:
OSError: [Errno 22] Invalid argument: '\example\x0cile.pck'
EDIT:
Solved! The right command is:
file = open("example/file.pck", "wb")
Use forward slashes
open("/example/file.pck", "wb")
Your problem is likely that backslashes were being interpreted as escape sequences.
You need to use forward slashes and also it seems that the example folder you trying to access doesn't exist. That's probably because you wanted to enter relative address but you entered an absolute one. So it should be:
open("example/file.pck", "wb")
Paths can be tricky, especially if you want to run your code on Unix-based and Windows systems. You can avoid many problems by using os.path which generates paths that will work on any os.
To open a new file use the 'w+' option instead of 'rw'.
In your case:
import os
file_path = os.path.join(os.path.curdir, 'file.pck')
file = open(file_path,'w+')

Categories

Resources