I'm getting the following error when attempting to open a new file with today's date.
Traceback (most recent call last):
File "C:\BenPi\stacking\pi3\red_RTS\iotest.py", line 6, in <module>
f = io.open('%s',today, 'w')
TypeError: an integer is required
Here is my code
import datetime
import io
import os
today = datetime.date.today().strftime('%m_%d_%Y')
print (today)
f = io.open('%s',today, 'w')
f.write('first line \n')
f.write('second line \n')
f.close()
It is my understanding that this is an issue that arises when someone inadvertently uses os.open() instead of io.open(), which is why I specified the io option. It should be noted that the same error comes up regardless if I import the os module.
I'm using python 3.2.5
Thoughts?
You're not formatting correctly, you're using , instead of %:
f = io.open('%s'%today, 'w')
Besides, you can just do:
f = io.open(today, 'w')
The line
f = io.open('%s',today, 'w')
should have '%s' first argument the first argument must be the file name.
If you write it like:
f = io.open(today, 'w')
Just works. Also consider using the "with" statment so in case of an exception the stream will be close anyway such as:
with io.open(today, 'w') as f:
f.write("hello world")
I hope I have been helpful.
Related
I am trying to write to a .txt file and then copy it into a second .txt file.
from sys import argv
script, send_file, get_file = argv
in_file = open(send_file, "r+")
in_file.write("I'm sending information to the receiver file.")
open(get_file, "w")
get_file.write(f"{in_file}")
But I keep getting the same error:
Traceback (most recent call last):
File "ex15_test.py", line 11, in <module>
get_file.write(f"{in_file}")
AttributeError: 'str' object has no attribute 'write'
Then I put open(get_file, "w") and get_file.write(f"{in_file}") inside of a variable and get no error whatsoever.
out_file = open(get_file, "w")
out_file.write(f"{in_file}")
But then this is what ends up being written into the second file:
<_io.TextIOWrapper name='sender.txt' mode='r+' encoding='cp1252'>
Do you know what I'm doing wrong?
Why did it work when I used the variables in the second code?
In open(get_file, "w"), get_file is the name of the file, it's a string.
You need to write to a file object, as you did to read in the first part of the code. So, it would be:
f = open(get_file, "w")
f.write(f"{in_file}")
f.close()
Note that you forgot to close both of your files in your code.
The good practice, though, is to use a context manager that will take care of the closing for you, whatever happens in your code (exception, ...)
So, the best way to do it would be:
with open(get_file, "w") as f:
f.write(f"{in_file}")
Sorry for messy code but this should do what you want i think
from sys import argv
script, send_file, get_file = argv
in_file = open(send_file, "r+")
in_file.write("I'm sending information to the receiver file.")
in_file.close()
in_file_2 = open(send_file, "r")
in_file_text = in_file_2.read()
in_file_2.close()
secondFile = open(get_file, "w")
secondFile.write(f"{in_file_text}")
secondFile.close()
What I Want
I have written a code that opens a file (currentcode) gets it's text finds it in another file (text.txt) and replaces currentcode with a new int.
My Code
import os
currentcode = open('currentcode.txt','r+')
code = currentcode.read()
print('Choose File: ')
print('1: File One > ')
file = input('Enter Number Of File: ')
file = 'C:/text.txt'
old_text = code
new_text = str(int(code) + 1)
print('Opened File')
f1 = open(file, 'r')
f2 = open(file, 'w')
f2.write(replace(old_text, new_text))
currentcode.write(new_text)
f1.close()
f2.close()
Output After Running
When I Run This Code I Get:
Choose File:
1: File One >
Enter Number Of File: 1
Opened File
Traceback (most recent call last):
File "C:\Users\DanielandZoe\Desktop\scripys\Replace.py", line 18, in <module>
f2.write(replace(old_text, new_text))
NameError: name 'replace' is not defined
NameError: name 'replace' is not defined
That means python couldn't find a module, class or function called 'replace'.
If you want to replace text on a file, you need to get its contents as a string, not as a file-like object (like you're doing now), then you replace the contents using the replace method on your string and finally, write the contents to the desired file.
string.replace() is a method for strings:
https://docs.python.org/2/library/string.html#string.replace
what is in f2? Not a string. You should read the lines of the file.
So I'm trying to use the csv module in python 3.3.2 but I am getting this error.
Traceback (most recent call last):
File "C:\Users\massi_000\Desktop\csv.py", line 1, in <module>
import csv
File "C:\Users\massi_000\Desktop\csv.py", line 4, in <module>
csv.reader(f)
AttributeError: 'module' object has no attribute 'reader'
Obviously I'm going something stupendously wrong but all the code I am using is below and it looks fine. Has something changed in this version that has rendered this code unusable or..?
import csv
f = open("test.csv")
csv.reader(f)
for row in csv_fi:
print(row)
f.close()
You have named your file csv.py and this clashes with the csv module from the Python standard library.
You should rename your own file to something else so that import csv will import the standard library module and not your own. This can be confusing but this is a good rule-of-thumb going forward: avoid giving your own Python files names that are the same as modules in the standard library.
As #Simeon Visser said, you have to rename your file but you have some other issues with your code as well. Try this:
import csv
with open('test.csv', newline='') as f:
reader = csv.reader(f, delimiter=' ')
for row in reader:
print (', '.join(row))
i have been working on a python tutorial and have come across a problem which i simply cannot work out. google has not turned up anything specific and after a few hours away and much trial and error i still cannot work it out.
anyway, the below code is a simplified version of the tutorial. it works fine and prints out that my file is 17 bytes long:
from sys import argv
from os.path import exists
script, file1 = argv
file_open = open(file1)
file_read = file_open.read()
print "the file is %s bytes long" % len(file_read)
then the tutorial asks to merge lines 6 and 7 into a single line. if i do it like this it works:
from sys import argv
from os.path import exists
script, file1 = argv
file_read = open(file1).read()
print "the file is %s bytes long" % len(file_read)
but, if i do it like like this then i get an error message which says TypeError: object of type 'file' has no len():
from sys import argv
from os.path import exists
script, file1 = argv
file_read = open(file1, "r+")
print "the file is %s bytes long" % len(file_read)
my problem is i cannot work out why that error message is occurring when i am adding the "r+" to make sure the open file is read. ( although, is it true that read is default anyway so maybe even adding the r+ is unnecessary )
any help would be much appreciated. many thanks :)
I think you forgot the .read() in:
file_read = open(file1, "r+")
so file_read is a file object. Try with:
file_read = open(file1, "r+").read()
and it will return a string as expected.
Regardless of whether you open it in r mode, r+ mode, or any other mode, opening a file with the open built-in returns a file object:
>>> open('test.txt', 'r+')
<open file 'test.txt', mode 'r+' at 0x013D9910>
>>> type(open('test.txt', 'r+'))
<type 'file'>
>>>
Moreover, you cannot use the len built-in on this object:
>>> len(open('test.txt', 'r+'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'file' has no len()
>>>
This is because, technically, a file object has no length. It is just a pointer to a certain file.
As you noted, the way to fix the problem is to first invoke the file object's read method. Doing so will return the file's contents as a string, which you can then use len on:
>>> open('test.txt', 'r+').read()
'hello world'
>>> len(open('test.txt', 'r+').read())
11
>>>
In the second example you are trying to find the length of the file pointer, which is not possible. SO add:
file_read.read()
instead of just file_read
When using len, it only accepts objects with a certain type if you're passing in an object with <type 'file'> it will throw an exception.
>>> f = open('/some/file/path', 'r+')
>>> type(f)
<type 'file'>
>>>
>>> type(f.read()) # the read method returns an object with type 'str'
<type 'str'>
Here f.read() returns a str object.
tempfile.mkstemp() returns:
a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.
How do I convert that OS-level handle to a file object?
The documentation for os.open() states:
To wrap a file descriptor in a "file
object", use fdopen().
So I tried:
>>> import tempfile
>>> tup = tempfile.mkstemp()
>>> import os
>>> f = os.fdopen(tup[0])
>>> f.write('foo\n')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IOError: [Errno 9] Bad file descriptor
You can use
os.write(tup[0], "foo\n")
to write to the handle.
If you want to open the handle for writing you need to add the "w" mode
f = os.fdopen(tup[0], "w")
f.write("foo")
Here's how to do it using a with statement:
from __future__ import with_statement
from contextlib import closing
fd, filepath = tempfile.mkstemp()
with closing(os.fdopen(fd, 'w')) as tf:
tf.write('foo\n')
You forgot to specify the open mode ('w') in fdopen(). The default is 'r', causing the write() call to fail.
I think mkstemp() creates the file for reading only. Calling fdopen with 'w' probably reopens it for writing (you can reopen the file created by mkstemp).
temp = tempfile.NamedTemporaryFile(delete=False)
temp.file.write('foo\n')
temp.close()
What's your goal, here? Is tempfile.TemporaryFile inappropriate for your purposes?
I can't comment on the answers, so I will post my comment here:
To create a temporary file for write access you can use tempfile.mkstemp and specify "w" as the last parameter, like:
f = tempfile.mkstemp("", "", "", "w") # first three params are 'suffix, 'prefix', 'dir'...
os.write(f[0], "write something")