I'm trying to write a function that would use a loop to write multiple files, but it's not succeeding. Here are the code, and the result. The directory does exist; I was able to write, read, and append single files to it with no problem. This was done in the ordinary Python 3.9 interactive command line window on Windows 10.
def writepages(i):
for j in range(i):
name = f"0{j}0page.html"
file = open(f'C:\\Users\\cumminjm\\Documents\\{name}', 'r+')
file.close()
>>>
>>> writepages(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in writepages
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\cumminjm\\Documents\\000page.html'
Unlike "w" or "a", "r+" requires that the file already exist; it does not create the file if it does not already exist.
You should use a different file mode — such as:
w to open a (possibly new) file, and empty it if it exists.
a to open a (possibly new) file, but not empty it.
x to open a new file and fail with FileExistsError if it exists.
As #chepner pointed out, r+ opens an existing file for read and write.
According to this answer you can also use os.mknod("newfile.txt"), but it requires root privilege on macOS.
It's a bit off-topic, but you might like to know about pathlib, which gives you an OS-agnostic way to handle file paths, and using a context for the file opening, which is safer than open/close. Here's how I'd probably write that function:
import pathlib
def writepages(i):
"""Write i HTML pages."""
for j in range(i):
fname = pathlib.Path.home() / 'Documents' / f'0{j}0page.html'
with open(fname, 'x') as f:
f.write('')
return
Related
I am trying to open a specific file in the archive and then write some content to it. I am using the zipfile.open() function to get access to the file:
import zipfile
my_zip = zipfile.ZipFile('D:\\files\\acrhive.zip')
with my_zip.open('hello.txt', 'w') as my_file:
my_file.write(b'Hello')
my_zip.close()
However, it gives me a warning about duplicate file called 'hello.txt'. After that I get the following error:
ValueError: write() requires mode 'w', 'x', or 'a'
What am I doing wrong here?
My full traceback:
D:\python\lib\zipfile.py:1506: UserWarning: Duplicate name: 'hello.txt'
return self._open_to_write(zinfo, force_zip64=force_zip64)
Traceback (most recent call last):
File "D:\files\python.py", line 8, in <module>
with my_zip.open(file, 'w') as my_file:
File "D:\python\lib\zipfile.py", line 1506, in open
return self._open_to_write(zinfo, force_zip64=force_zip64)
File "D:\python\lib\zipfile.py", line 1598, in _open_to_write
self._writecheck(zinfo)
File "D:\python\lib\zipfile.py", line 1699, in _writecheck
raise ValueError("write() requires mode 'w', 'x', or 'a'")
ValueError: write() requires mode 'w', 'x', or 'a'
Right now you're opening the file in the archive file for writing, but the archive file itself only for reading (the default mode).
The key here is that to the file system, the files inside the archive do not really exist as real files. To the file system they are just bytes inside the archive file. The zipfile library, like many file managers, just goes out of its way to give them to you as virtual files - something that mostly looks and works like a normal file to make it easier to work with them the same way.
So try opening the zip file itself for writing too:
zipfile.ZipFile('D:\\files\\archive.zip', 'w')
Couple notes:
Both zip file and the file in the zip file should be opened for writing.
In the question code you posted, it looks like you have a typo in the zip file name: acrhive.zip vs archive.zip. If my answer code starts failing for you with "file not found", that might be why.
You should just open the zip file with a context manager too, just as with other files and file-like things.
So putting it all together:
with zipfile.ZipFile('D:\\files\\archive.zip', 'w') as my_zip:
with my_zip.open('hello.txt', 'w') as my_file:
my_file.write(b'Hello')
I'm trying to read this .txt file through Python (3.6.5), using SublimeText3 (3.1.1). learning_python.txt is in the same directory as my python program. I tried to make it an absolute filepath but getting FileNotFoundError either way. I also tried running it through Terminal with the same outcome. Is the code wrong?
filename = 'learning_python.txt'
print("--- Reading in the entire file:")
with open(filename) as f:
contents = f.read()
print(contents)
Traceback is:
--- Reading in the entire file:
Traceback (most recent call last):
File "C:\Users\sulli\Documents\Coding\Python Crash Course\Ch_10_Files_Exceptions\about_python.py", line 6, in <module>
with open(filename) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/sulli/Documents/Coding/Python Crash Course/Ch_10_Files_Exceptions/learning_python.txt'
Looks like the issue here was I had named learning_python.txt file with the .txt at the end just like it is in the code. When I deleted the .txt on the text file itself, it worked in Python to find learning_python.txt. Python must have seen it as learning_python.txt.txt.
How do I turn this format of TXT file into a CSV file?
Date,Open,high,low,close
1/1/2017,1,2,1,2
1/2/2017,2,3,2,3
1/3/2017,3,4,3,4
I am sure you can understand? It already has the comma -eparated values.
I tried using numpy.
>>> import numpy as np
>>> table = np.genfromtxt("171028 A.txt", comments="%")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Smith\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\npyio.py", line 1551, in genfromtxt
fhd = iter(np.lib._datasource.open(fname, 'rb'))
File "C:\Users\Smith\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\_datasource.py", line 151, in open
return ds.open(path, mode)
File "C:\Users\Smith\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\_datasource.py", line 501, in open
raise IOError("%s not found." % path)
OSError: 171028 A.txt not found.
I have (S&P) 500 txt files to do this with.
You can use csv module. You can find more information here.
import csv
txt_file = 'mytext.txt'
csv_file = 'mycsv.csv'
in_txt = csv.reader(open(txt_file, "r"), delimiter=',')
out_csv = csv.writer(open(csv_file, 'w+'))
out_csv.writerows(in_txt)
Per #dclarke's comment, check the directory from which you run the code. As you coded the call, the file must be in that directory. When I have it there, the code runs without error (although the resulting table is a single line with four nan values). When I move the file elsewhere, I reproduce your error quite nicely.
Either move the file to be local, add a local link to the file, or change the file name in your program to use the proper path to the file (either relative or absolute).
def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
data = Source_obj.read()
I am having trouble opening this file while located in a sub-directory directly underneath my Python file... is there a better way to open files from ANY directory on my computer?
FileNotFoundError: [Errno 2] No such file or directory: 'WebSource\\EXAMPLE SOURCE.htm'
I can't read from the file because I get the following error:
C:\python34\python.exe G:\Robot\test.py
Process started >>>
Traceback (most recent call last):
File "G:\Robot\test.py", line 118, in <module>
functION()
File "G:\Robot\test.py", line 64, in functION
data = Source_obj.read()
AttributeError: 'str' object has no attribute 'read'
<<< Process finished. (Exit code 1)
================ READY ================
BTW: The file to be read is just a source file from an HTML Chrome webpage.
EDIT
I'm looking for more help with the path and wondering why I get the first mentioned Traceback regarding the path
os.path.relpath() returns a string, not an open file object. You'll need to open a file first; use the open() function:
def functION():
Source_obj = path.relpath(r"WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as fileobj:
data = fileobj.read()
with here treats the file object as a context manager; when the indented codeblock under the statement is exited (either because the code completed or an exception occurred), the file object will automatically be closed.
Your Source_obj is just a string, not a file.
def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as f:
data = f.read()
By open()-ing it you can read from the file. Using the with context manager, the file will be properly closed for you when you leave that block of code.
Could you helpme to make this exmaple work?
I'd like to load a serialized dict if it exists, modify it and dump it again. I think I have a problem with the mode I'm using to open the file but I don't know the correct way.
import os
import cPickle as pickle
if os.path.isfile('file.txt'):
cache_file = open('file.txt', 'rwb')
cache = pickle.load(cache_file)
else:
cache_file = open('file.txt', 'wb')
cache = dict.fromkeys([1,2,3])
# modifications of cache
pickle.dump(cache, cache_file)
cache_file.close()
Run it twice to see the error:
Traceback (most recent call last):
File "example.py", line 11, in <module>
pickle.dump(cache, cache_file)
IOError: [Errno 9] Bad file descriptor
'rwb' is not correct file open mode for open(). Try 'r+b'.
And after you have read from file, you have cursor positioned at the end of file, so pickle.dump(cache, cache_file) will append to the file (which is probably not what you want). Try cache_file.seek(0) after pickle.load(cache_file).
For each load, you need to open(with mode='rb'), load, and close the file handle.
For each dump, you need to open(with mode='wb'), dump, and close the file handle.
You have opened the file for reading and writing - i.e. random access. When you initially read the file you leave the file index position at the end of the file, so when you later write the data back you are appending to the same file.
You should open the file in read mode, read the data, close it, then reopen in write mode.