How to create a file in a folder - python

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+')

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

Python can't find where my txt file is, how can i link it or where do i need to put the file?

Python can't find where my .txt file is, how can I find the correct path to it or where do I need to put the file?
I tried the following but got an error:
with open("C:\Users\raynaud\Downloads\notlar.txt","r",encoding="utf-8") as file:
with open("dosya.txt","r",encoding= "utf-8") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'dosya.txt'
If you are not using absolute path, you must place the file in the same directory as the script is. On absolute paths you should not use \ like "C:\Users\UserName\", because \ is the escape character in Python (and many more languages). You must use it like this: "C:\\Users\\UserName\\"
Have you checked your current directory? It might be pointing to somewhere unexpected. Try:
import os
os.getcwd()

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 solve IOError: [Errno 2] No such file or directory: in Biopython?

I am trying to parse a fasta file in Biopython using the following code.How can I solve this error?
from Bio import SeqIO
handle = open("C:/Users/Desktop/kk.fasta", "rU")
File "<pyshell#19>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'kk.fasta'
I am getting the above error. But my file is already there. I am using windows7 OS , python 2.7 and Biopython 1.57. Any suggestions please.
try:
import os
print os.path.isfile(r"C:\Users\Desktop\kk.fasta")
if the output is true, you can try to replace the string in the original code and see if it works. If not, make sure there is no typo in the path.
the small r means raw. It will escape all \ to \\ to make sure the path is valid (\n won't become a newline)
Your path is wrong.
Open up explorer and put in this path:
c:\Users\
This might help you to correct the path. The next directory below Users will be a username, or Default, not Desktop.

What is wrong with this code to open a file?

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)

Categories

Resources