a01:01-24-2011:s1
a03:01-24-2011:s2
a02:01-24-2011:s2
a03:02-02-2011:s2
a03:03-02-2011:s1
a02:04-19-2011:s2
a01:05-14-2011:s2
a02:06-11-2011:s2
a03:07-12-2011:s1
a01:08-19-2011:s1
a03:09-19-2011:s1
a03:10-19-2011:s2
a03:11-19-2011:s1
a03:12-19-2011:s2
this is saved in animallog1.txt. How would I import this file so that it can be used to write code, or answer questions using the above data.
I have tried:
open('C:/animallog1.txt', 'r')
but it does not work and states
FileNotFoundError: [Errno 2] No such file or directory: 'C:/animallog1.txt'
Could someone please help me fix this
open('C:\\animallog1.txt', 'r')
Does file animallog1.txt exists?
On Windows you should be care for the backsplash.
file = open('c:\\path\\to\\file', 'r')
or
file = open(r'c:\path\to\file', 'r')
Check your workspace, u can use os.chdir() to change your directory to c:\?
First, if you're using Windows, you have to use backslashes. There are a couple ways to do that: one is with double backslashes as others have pointed out, another is using the various constants and functions in the os and os.path libraries:
import os
filename = "C:" + os.sep + "animallog1.txt"
Second, the "proper" way to do this is with a with statement:
with open(filename) as f: #'r' is default
for line in f:
a, date, s = line.split(":")
# ...
What the with statement does is guarantee that the file gets closed on leaving the with block. Otherwise the file doesn't get closed until the Python garbage collector gets around to it.
Related
I have created a script to write to a file in python:
a_file = open("file:///C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
The absolute path of the file is: file:///C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt
However, the program does not write(append) to the file. I can run the program, but nothing happens to the file. The strange thing is that it works if I put the file in the same directory as the script and run the script using the location "testfileTryToOVERWRITEME.txt". That is:
a_file= open("testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
This works 100% and appends to the file. But when I use the absolute path of the file, it never works. What is wrong?
Edit
I tried everything and it still doesn't work
My code:
a_file= open("C://Users//xdo//OneDrive//Desktop//Javascript//read%20and%20write//testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
a_file.close()
This did not work. I also tried:
a_file= open("C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
a_file.close()
This did not work
Edit (finally works)
It finally works. I replaced the "%20" with a regular space " " and used the pathlib module like this:
from pathlib import Path
filename = Path("C:/Users/qqWha/OneDrive/Desktop/Javascript/read and write/testfileTryToOVERWRITEME.txt")
f = open(filename, 'a+')
f.write("Hello")
And now it writes to the file.
It also works using "with". Like this:
with open("c:/users/xdo/OneDrive/Desktop/Javascript/read and write/testfileTryToOVERWRITEME.txt", "a+") as file:
file.write("hello")
Try doing "with". Also, replace the %20 with a space. Python does not automatically decode this, but you shouldn't have an issue using spaces in the instance below.
with open("c:/users/xdo/OneDrive/Desktop/Javascript/read and write/testfile.txt", "a+") as file:
file.write("hello")
In this case, if the file doesn't exist, it will create it. The only thing that would stop this is if there are permissions issues.
This will work. when we open a file in python using the open function we have to use two forward slashes.
f = open('C://Users//xdo//OneDrive//Desktop//Javascript//read%20and%20write//testfileTryToOVERWRITEME.txt', 'a+')
f.write("writing some text")
f.close()
or you can use another way in which you have to use from pathlib import Path package.
from pathlib import Path
filename = Path("C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt")
f = open(filename, 'a+')
f.write("Hello")
f.close()
If still, your problem exists, then try another absolute path like "C:/Users/xdo/OneDrive/Desktop/testfileTryToOVERWRITEME.txt"
At the moment I have a piece of code that writes the output from previous lines into a .html file in the same location as where the .py file is at....
I am looking for a line of code where it will simply write into the folder ./output/ of the same location the .py file is located
Below is the code I have but cant seem get it to work...
fullhtml = '<html><body><pre><h1>%s</h1><h2>#KCBB</h2><table>%s</table></pre></body></html>'%(end_date,myhtml)
with open('%s KCBB Bands.html'%end_date, 'w') as f:
f.write(fullhtml)
it usually writes it to that location, however, you can use __file__ to refer to that location.
__file__ will give you the python file root.
import os
print(os.path.dirname(os.path.realpath(__file__)))
As mentioned, the filename of your script is in __file__ (unless you are running in an IDE like jupyter). You can just use it with functions in the os module to get that path you want.
import os
fullhtml = '<html><body><pre><h1>%s</h1><h2>#KCBB</h2><table>%s</table></pre></body></html>'%(end_date,myhtml)
filename = os.path.join(os.path.dirname(__file__), "output",
'%s KCBB Bands.html' % end_date)
with open(filename, 'w') as f:
f.write(fullhtml)
Nevermind, i managed to figure it out....
Replacing
with open('%s KCBB Bands.html'%end_date, 'w') as f:
With
with open('./output/%s - KCBB Signal Output.html'%end_date, 'w') as f:
Notice the ./output/ < thats the directory i wanted the files to go into.
I'm new here,too. I think you're trying to keep your output files in a subdirectory of the working directory where the .py files are, is that right? If so, I think you just need to include the folder name in the open statement like so:
with open('output/%s KCBB Bands.html'%end_date, 'w') as f:
f.write(fullhtml)
The folder must already exist though, or you'll get an exception.
I have a noob python question... so bear with me.
Can I open multiple files before closing the previos.
So... can I run
import os
files=[]
for file in os.listdir(os.curdir):
files.append(open(file,'w'))
Then edit each file as I want and finish with
for file in files:
file.close()
Thanks in advance
Seems legit and works fine.
Doing operations would be hard for you this way. the list "files" doesn't contain the filenames. You would not know which file is what.
It is perfectly fine to open each file using open and later close all of them. However, you will want to make sure all of your files are closed properly.
Normally, you would do this for one file:
with open(filename,'w') as f:
do_something_with_the_file(f)
# the file is closed here, regardless of what happens
# i.e. even in case of an exception
You could do the same with multiple files:
with open(filename1,'w') as f1, open(filename2,'w') as f2:
do_something_with_the_file(f)
# both files are closed here
Now, if you have N files, you could write your own context manager, but that would probably be an overkill. Instead, I would suggest:
open_files = []
try:
for filename in list_of_filenames:
open_files.append(open(filename, 'w'))
# do something with the files here
finally:
for file in open_files:
file.close()
BTW, your own code deltes the contents of all files in the current directory. I am not sure you wanted that:
for file in os.listdir(os.curdir):
files.append(open(file,'w')) # open(file,'w') empties the file!!!
Maybe you wanted open(file, 'r') or open(file, 'a') instead? (see https://docs.python.org/2/library/functions.html#open)
Your solution will certainly work but the recommended way would be to use contextmanager so that the files gets handled seamlessly. For example
for filename in os.listdir(os.curdir):
with open(filename, 'w') as f:
# do some actions on the file
The with statement will take care of closing the file for you.
I went through couple answers on forum already but without any success.
I am using Linux mint, Python 3.6.0 and i am trying to open CSV in Python but then error occurs:
file = open("~/Desktop/xyz/city.csv", "rb")
FileNotFoundError: [Errno 2] No such file or directory: '~/Desktop/xyz/city.csv'
My code:
import csv
file = open("~/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
I also tried to move the file to desktop as in some answers i found, instead of path i used "city.csv". Still doesn't work.
Completely new to Linux and just can't find why this isn't working.
Each reply appreciated!
You should'nt use '~' to specify the path of your directory but the full path instead. E.g. :
import csv
file = open("/home/user/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
If you need to use the tilde, you should then use os.path.expanduser('~/Desktop/xyz/city.csv'). E. g. :
import csv
file = open(os.path.expanduser("~/Desktop/xyz/city.csv"), "rb")
reader =csv.reader(file)
The reason for that is that the "tilde expansion" is a user interface feature that is not recognized by the file system: http://www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion
Try using the full file path, something like this:
file = open("/home/[username]/Desktop/xyz/city.csv", "rb")
Usually ~ does not expand properly. I have found that when it is needed, put $HOME environment variable value into a python variable and then use join to attach it as a prefix to the file name relative position. This also allows you to move the file to a different location and create a function that will allow you to redefine the prefix.
I'm new to python and working on a way to open a file named acne.txt which is inside my define folder in the same python34 folder as my code.
The code I've written for the same is:
NN_is = [word for word,pos in tagged_sent if pos == 'NN']
print(NN_is[0])
searchfile = open(r"define/NN_is[0].txt", "r")
file_contents = searchfile.readlines()
searchfile.close()
The variable NN_is[0] when printed yields acne. Can someone help me in solving this problem.
Thank you in advance.
Use os.path.join() to concatenate the directory and file name, and use str.format() to construct the string for the file name:
import os.path
path = os.path.join('define', '{}.txt'.format(NN_is[0]))
with open(path) as searchfile:
file_contents = searchfile.readlines()
...
I also recommend that you open the file within a with statement. This ensures that the file will always be closed, even if there is an error. It's also handy because you don't need to explicitly close the file - it will be closed when the with statement goes out of scope.