I can't open the file as a write file.
script = argv
filename = argv
print(f"We're going to erase {filename}. ")
print("If you don't want that, hit CTRL-C (^C). ")
print("If you do want that, hit RETURN. ")
input("?")
print("Opening the file...")
target = open(filename, 'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines. ")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file. ")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it. ")
target.close()
It's giving this error:
line 14, in <module>
target = open(filename, 'w')
TypeError: expected str, bytes or os.PathLike object, not list
If I execute the code from terminal, It's giving me a syntax error for the last double quote of the first print statement.
line 6
print(f"We're going to erase {filename}. ")
^
SyntaxError: invalid syntax
To solve this I've changed the f-string to format.
print("We're going to erase {}. ".format(filename))
After I executed the code It gave me another error:
File "ex16.py", line 11, in <module>
input("?")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
I don't know what to do.
I assume argv is sys.argv, and sys.argv is a list of the script name itself, and all arguments passed on the command line. Thus, you need to index it:
script = argv[0]
filename = argv[1]
I think you should add some checks to your program to check whether the correct amount of arguments have been passed, and the file really exists, etc., but that is up to you.
Related
I want to truncate my file after reading the content of it, but it does not seem to do so and additions to the file are made after the existing content, instead of the beginning of a file.
My code is as follows:
from sys import argv
script, filename = argv
prompt= '??'
print("We're going to erase %r." %filename)
print("If you don't want that, hit CTRL-C.")
print("If you do want it, hit ENTER.")
input(prompt)
print("Opening the file...")
target = open(filename,'r+')
print(target.read())
print("I'm going to erase the file now!")
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you 3 lines:")
line1 = input('Line 1: ')
line2 = input('Line 2: ')
line3 = input('Line 3: ')
print("I'm going to write these to the file now!")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally we close the file! Please check and see if the file
has been modified!")
target.close()
To truncate a file to zero bytes you can just open it with write access, no need to actually write anything. It can be done simply:
with open(filename, 'w'): pass
However, using your code you need to reset the current file position to beginning of file before the truncate:
....
print("Truncating the file. Goodbye!")
target.seek(0) # <<< Add this line
target.truncate()
....
Example run (script is gash.py):
$ echo -e 'x\ny\nz\n' > gash.txt
$ python3 gash.py gash.txt
We're going to erase 'gash.txt'.
If you don't want that, hit CTRL-C.
If you do want it, hit ENTER.
??
Opening the file...
x
y
z
I'm going to erase the file now!
Truncating the file. Goodbye!
Now I'm going to ask you 3 lines:
Line 1: one
Line 2: two
Line 3: three
I'm going to write these to the file now!
And finally we close the file! Please check and see if the file has been modified!
$ cat gash.txt
one
two
three
$
To Truncate just write:
f = open('filename', 'w')
f.close()
I'm unable to get this exercise running properly:
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("If you don't want that, CRTL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename, 'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it")
target.close()
When I run this, it doesn't actually overwrite the file. It creates a new file that includes the three lines I entered. I know truncate is supposed to empty the file, so I don't know why ut's creating another file. I'm not sure what exactly is wrong, let me know. Thanks
from sys import argv
script,filename = argv
print "Will truncate the file : %s" %filename
print "If you wish to continue press \"Return\" or press CNTRL-C"
raw_input("?")
target = open(filename,"w")
print "We are truncating the file"
target.truncate()
print "File is truncated"
print "Now enter the three lines to add into the file"
line1 = raw_input("Line_1 : ")
line2 = raw_input("Line_2 : ")
line3 = raw_input("Line_3 : ")
print "Adding these line is in progress"
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "Writter is completed"
target.close()
**print "Here is the new file :\n",open(target,mode='r', buffering=-1).read()**
target.close()
I am trying to truncate a file and then writting few lines in it , after that when Iclose the file and try to rreopen it , it's giving me the below error
Error is in the highlighted part .. can you please help me what could
be the error
You are getting this error because open is looking for a file name, and you're passing to it the file object itself.
From the docs on open function:
The first two arguments are the same as for stdio‘s fopen(): name is
the file name to be opened, and mode is a string indicating how the
file is to be opened.
When I have a text file and the first line is "hello", if I write
reader = open('txtfile.txt', 'r')
line = reader.readline()
print(line)
it will print "hello".
Then, when I write
input = input()
if line == input:
print('they are the same')
else:
print('they are not the same')
it says that they are not the same, even when the input is "hello". Is this a problem with my code or does readline() not allow for this?
I suggest using with open() as.. : because...
This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
Your program would become:
with open('txtfile.txt', 'r') as f:
for line in f:
answer = input('\nContent?')
if line.replace('\n','') == answer:
print('they are the same')
else:
print('they are not the same')
Also, avoid naming your variable 'input' since it will shadow the name of the build-in input().
If your file is:
hello
Hi
bye
then your first line would be 'hello\n'. replace() removes that \n before the comparison.
I am trying to build a function that asks the user to input the name of a file, opens the file, reads its contents, prints the contents of the file on the screen, and closes the file. If no such file exists, it's okay if the script crashes. When I run the function, it gives me: NameError: name 'myInput' is not defined, and I'm not sure how to fix it.
Here is what I have so far:
print(input('Please enter the name of a file that you want to open.' + myInput))
with open(r"C:\Python32\getty.txt", 'r') as infile:
data = infile.read()
print(data)
Help if you can..
myInput is an undefined variable, and I can't fathom what you had in mind by using it.
Maybe where you show the code...:
print(input('Please enter the name of a file that you want to open.' + myInput))
with open(r"C:\Python32\getty.txt", 'r') as infile:
you actually meant something very different, e.g like...:
myInput = input('Please enter the name of a file that you want to open.')
with open(myInput, 'r') as infile:
...?
In your first line, you have:
print(input('Please enter the name of a file that you want to open.' + myInput))
do you have myInput defined? You need to define it. If you don't have it defined before that line, your script will crash.
This can be gleaned from your helpful error message:
NameError: name 'myInput' is not defined
Which means that the variable myInput is not defined, so the compiler doesn't know what to put there.
I think something like this would solve your problem
fileName = raw_input("Please enter the name of a file that you want to open. ")
fileObject = open(fileName, "r")
fileText = fileObject.read()
print(fileText)