This question already has answers here:
open() in Python does not create a file if it doesn't exist
(17 answers)
Closed 2 years ago.
I'm trying to write to a txt file but faced the following error message: [Errno 2] No such file or directory: 'results.txt'. The results.csv file contains data separated by pipeline delimiters. May I know what went wrong and how do I solve this?
results_path = "results.csv"
dest_path = "results.txt"
def row_count(results_path):
return len(open(results_path).readlines())
def add_header_footer(results_path, dest_path, file_name, date_today):
with open(results_path) as from_file, open(dest_path) as to_file:
header = 'H|ABC|' + file_name + '|' + date_today + '\n'
footer = 'E|' + str(row_count(results_path)) + '|\n'
to_file.write(header)
shutil.copyfileobj(from_file, to_file)
to_file.write(footer)
add_header_footer(results_path, dest_path, 'Results_Today', '20190818')
You should use open destination file with the w+ mode. It tries to write to the file and if it does not exist then it creates the file. Change this part of your code and see whether it works.
open(dest_path, 'w+') as to_file
There are other modes too like, a+ for appending. Read more here
Python can find your file result_path.
Try to set your results_path variable as an Absolute path.
Normally that Error message is shown when you call a file which is not in the same level as your py file.
Hope this is helpful! :D
Related
This question already has answers here:
Character reading from file in Python
(9 answers)
Closed 2 years ago.
So the code I have copied an HTML file into a string and then changed everything to lower case except normal text and comments. The problem is it also changes the åäö into something the VS code can't recognise. What I can find is its a problem with the encoding but can't find anything about it on py3 and the solutions I found for py2 didn't work. Any help is appreciated and if you know how to improve the code plz tell me.
import re
import os
text_list = []
for root, dirs, files in os.walk("."):
for filename in files:
if (
filename.endswith(".html")
):
text_list.append(os.path.join(root, filename))
for file in text_list:
file_content = open(f"{file}", "r+").read()
if file.endswith(".html"):
os.rename(file, file.replace(" ", "_").lower())
code_strings = re.findall(r"<.+?>", file_content)
for i, str in enumerate(code_strings):
new_code_string = code_strings[i].lower()
file_content = file_content.replace(code_strings[i], new_code_string)
else:
os.rename(file, file.replace(" ", "_").lower())
file_content = file_content.lower()
open(f"{file}", "r+").write(file_content)
Open your file with codecs and use Unicode encoding.
Example:
import codecs
codecs.open('your_filename_here', encoding='utf-8', mode='w+')
Docs: Python Unicode Docs
This question already has answers here:
Why am I getting a FileNotFoundError? [duplicate]
(8 answers)
FileNotFoundError: [Errno 2] No such file or directory [duplicate]
(6 answers)
Closed 3 years ago.
i'm writing a program that write some website inside hosts file
but when i'm trying run the program it's show me an error that the directory is not found
import time
from datetime import datetime as dt
host_temp = "hosts"
host_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = "127.0.0.1"
website_list = ["www.facebook.com","www.instagram.com", "www.youtube.com"]
while True:
if dt(dt.now().year,dt.now().month,dt.now().day,20) < dt.now() < dt(dt.now().year,dt.now().month,23,1):
print("Working hours!!!")
with open(host_temp, "r+") as file:
content = file.read()
for website in website_list:
if website in content:
pass
else:
file.write(redirect + " " + website + "\n")
else:
print("Fun hours!!!")
time.sleep(5)
and this is the output
Working hours!!!
Traceback (most recent call last):
File "C:\Users\ALAA\AppData\Local\atom\app-1.38.2\hello\web site blocker\web_site_blocker.py", line 12, in <module>
with open(host_temp, "r+") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'hosts'
This error has nothing to do with the structure of your program. It is just saying that it cannot find the file you say exists. You need to check the filetype of your file (you can usually see it next to your file name or in the file's properties). The majority of files have an extension.
If your file is a text file (.txt), for example, your filename would be:
host_temp = "hosts.txt"
seems like your code should be like below with full path. if you don't provide full path then python will search for 'hosts' file where your py file is stored.
with open(host_path, "r+") as file:
Does open() in python create a file? If not, is there a function that does that? When I use this, it gives me
"IOError: [Errno 2] No such file or directory:
'/home/sanjiv/Desktop/COSURP/pyfiles/f1.txt'"
Was I not supposed to put the location to create the file? If not, where does it create it
f = open('/home/sanjiv/Desktop/COSURP/pyfiles/f1.txt', 'r+')
gpa = {'fall15':4.0, 'spr16':3.47, 'fall16':4.0}
for s in gpa:
f.write(str(s) + '\n')
f.close()
If you want to open the file for writing you should use the w as the second parameter (of the open function), and not r+.
The w will open the file for writing (and truncating the file if it already exists):
f = open('/home/sanjiv/Desktop/COSURP/pyfiles/f1.txt', 'w')
gpa = {'fall15':4.0, 'spr16':3.47, 'fall16':4.0}
for s in gpa:
f.write(str(s) + '\n')
f.close()
Note that if you want to open a file in the directory /home/sanjiv/Desktop/COSURP/pyfiles/ this directory must exists and you must have write-permissions to this directory.
This question already has answers here:
Why can't I make a file with a name like "InternetSpeedTest_11/24/21.csv"?
(2 answers)
Closed 6 months ago.
I'm writing a scraper to open a CSV, get a list of links, extract a specific HTML tag in the site (speechs) and save the content in a TXT file, named after the day the speech was given.
Here is was I accomplished:
#encoding:utf-8
import csv
import urllib
import lxml.html
import unicodedata
objeto = csv.reader(open('links.csv', 'rU'), dialect=csv.excel_tab)
for link in objeto:
connection = urllib.urlopen(link[0])
dom = lxml.html.fromstring(connection.read())
discurso = []
for d in dom.xpath('//div[#id="content-core"]/div/p/text()'):
discurso.append(d)
d1 = " ".join(discurso)
data = dom.xpath('//span[#class="documentPublished"]/text()[normalize-space()]')
data1 = [date.strip() for date in data]
make_string = "-".join(data1)
file = open(make_string+'.txt', 'w')
file= arquivo.write(d1)
file.close()
I was able to extract the date and the speech, but the final step is not working. When trying to save the speech a in TXT file, the IDLE shows me the message
IOError: [Errno 2] No such file or directory: '17/12/2010 23h39,.txt'
I've tried using 'w' and 'a' when creating the file, but it failed. What am I doing wrong?
The problem is that it expects to find a directory 17 and a subdirectory 12 under that because / is used to denote directories. I suggest replacing all / characters with -.
This question already has answers here:
open() in Python does not create a file if it doesn't exist
(17 answers)
Closed 8 years ago.
I've got the following Python code:
class Server(object):
def __init__(self, options):
self.data_file = '/etc/my_module/resources.json'
# Triggered when new data is received
def write(self, data):
try:
f = open(self.data_file, 'w')
json.dump(data, f)
except Exception, e:
print e
finally:
f.close()
If the file /etc/my_module/resources.json does not exist then I get an error message when I call the write method:
[Errno 2] No such file or directory: '/etc/my_module/resources.json'
If I create the file manually and call the write method again, then everything works and the json is written to the file.
I'm running my application with sudo: sudo python my_module.py, and I've added my user (vagrant) to /etc/sudoers.
So python won't create the file if it doesn't exist, on the grounds that it doesn't have permission to write to /etc, but it will happily write to the file if it does exist. Why is this?
Change
f = open(self.data_file, 'w')
To
f = open(self.data_file, 'w+')
Creating a new file involves writing a new file entry to the directory which requires write permissions on the directory. Modifying an existing file bypasses this.