Cannot read Excel chart properly with intended line of code - python

So this might be a simple solution but I can't seem to come up with it. When I use the following code I can open the file, read through it and do all the necessary functions, but if I use the commented line instead of the one underneath it gives me an error at line r = L[15] like it can't read it properly anymore. What can I do about this? If more code is needed I can provide it. Thanks!
def open_file():
while True:
file = input("Enter a file name: ")
try:
open(file)
return file
except FileNotFoundError:
print("Error. Please try again.")
print()
def read_file():
#fp = open_file()
fp = open("Texas_death_row.csv")
csv_fp = csv.reader(fp)
data = []
for L in csv_fp:
r = L[15]
g = L[16]
v = L[27]
T = (r,g,v)
my_list.append(T)
return data

Your open_file function is returning the variable file, that contains the string containing the filename, not the file object (file descriptor) which is what you can read and whatnot.
You should try something like this:
def open_file():
while True:
file = input("Enter a file name: ")
try:
f = open(file)
return f # Return the "file object", not the file name
except FileNotFoundError:
print("Error. Please try again.")
print()
PS: When you're dealing with files, don't forget to close them when you're done with them.

Related

I am trying to create a todo list in python

the code should take what i worte in the input and add it to the txt file but i get an error because of the path please take a look.
main = input("What Task Would You Like To Add? > ")
f = open("C:\tdl\tdlp\MyToDoList.txt", "w")
f.write("content added")
f.close()
f = open("MyToDoList.txt", "r")
print(f.read())
I have tried replacing file formats and paths

Trying to use os.path.exists via variables but getting an error

I have a file called serial.dll. The content of this file is another file's name:
a-2ED1-7156.dll
I also have 1 file called a-2ED1-7156.dll in the same directory.
When I try to check if the file exists by reading its name from serial.dll:
f = open('serial.dll', 'r')
serials = f.read()
if os.path.exists(serials):
print("ok")
else:
print("no")
Always results "no".
but:
file = 'a-2ED1-7156.dll'
if os.path.exists(file):
print("ok")
else:
print("no")
Always gives the correct result.
How can I check if the file a-2ED1-7156.dll exists by reading it from the serial.dll file?
Update Try:
f = open('serial.dll', 'r')
lines = f.readline()
for line in lines:
if os.path.exists(line):
print('ok')
else:
print("no")
results error:
no
no
no
no
no
no
no
no
no
no
no
ok
no
no
no
no
Supossing each file is in a separate line, you coud use
lines = f.readlines()
for line in lines:
if os.path.exists(line):
print('ok')
Or print only if all files exist, depending on what you want exactly.
Your problem is that lines in a file might end with the new-line character. File names usually don't have that character... For example, right now you're checking if the file a-2ED1-7156.dll\n exists - which is not. You simply need to strip() the lines before checking them as files:
f = open('serial.dll')
for line in f:
filename = line.strip()
if os.path.exists(filename):
print(f"{filename} exists")
else:
print(f"{filename} doesn't exist")

How can I open and read an input file and print it to an output file in Python?

So how can I ask the user to provide me with an input file and an output file?
I want the content inside the input file provided by the user to print into the output file the user provided. In this case, the user would put in this
Enter the input file name: copyFrom.txt
Enter the output file name: copyTo.txt
inside the input file is just the text "hello world".
Thanks. Please keep it as simple as you can if possible
If you just want to copy the file, shutil’s copy file does the loop implicitly:
import os
from shutil import copyfile
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
copyfile(openfile, outputfile)
This this post How do I copy a file in Python? for more detail
Here is an example that should work in Python3. The input and output file names would need to include the full path (i.e. "/foo/bar/file.txt"
import os
input_file = input('Enter the input file name: ')
output_file = input('Enter the output file name: ')
def update_file(input_file, output_file):
try:
if os.path.exists(input_file):
input_fh = open(input_file, 'r')
contents = input_fh.readlines()
input_fh.close()
line_length = len(contents)
delim = ''
if line_length >= 1:
formatted_contents = delim.join(contents)
output_fh = open(output_file, 'w')
output_fh.write(formatted_contents)
output_fh.close()
print('Update operation completed successfully')
except IOError:
print(f'error occurred trying to read the file {input_fh}')
update_file(input_file, output_file)
You can do this...
import os
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
if os.path.isfile(openfile):
file = open(openfile,'r')
output = open(outputfile,'w+')
output.write(file.read())
print('File written')
exit()
print('Origin file does not exists.')
To input the input-file and output-file names, simply use the input(s) function where s is the input message.
To get the "content inside the input file provided by the user to print into the output file," that would mean reading the input file and writing the read data into the output file.
To read the input file, use f = open(input_filename, 'r'), where the first argument is the filename and the second argument is the open mode where 'r' means read. Then letting readtext be the read text information of the input file, use readtext = f.read(): this returns the entire text content of f.
To output the read content to the output file, use g = open(output_filename, 'w'), noting that now the second argument is 'w', meaning write. To write the data, use g.write(readtext).
Please note that an exception will be raised if the input file is not found or the output file is invalid or not possible as of now. To handle these exceptions, use a try-except block.
This is effectively a file-copying operation in Python. shutil can serve as a useful alternative.
First you have to read the file and save it to some variable (here rd_data):
if os.path.exists(input_file_name):
f = open(input_file_name,"r")
rd_data = f.read()
f.close()
Then you have to write the variable to other file:
f = open(output_file_name,"w")
f.write(rd_data)
f.close()
The full code is given below:
import os
input_file_name = input("Enter file name to read: ")
output_file_name = input("Enter file name to write: ")
if os.path.exists(input_file_name):
f = open(input_file_name,"r")
rd_data = f.read()
f.close()
f = open(output_file_name,"w")
f.write(rd_data)
f.close()

python: check file extension and prompt again input if invalid file extension

problem
Doing a while loop to validate file extension. If a file extension is not .exe or .bat, ask user input again. I am looking for a solution without using import endswith break functions.
code
format = " "
while file[:-4] != ".bat" and file[:-4] != ".exe":
format = input("Enter file you like to open: ")
if format[:-4] == ".bat" or format[:-4] == ".exe":
callFunction(format)
else:
file = input("Enter file you like to open: ")
To follow Asking the user for input until they give a valid response and using os.path.splitext() to extract the file extension:
import os
ALLOWED_EXTENSTIONS = {".bat", ".exe"}
while True:
filename = input("Enter file you like to open: ")
extension = os.path.splitext(filename)[1]
if extension in ALLOWED_EXTENSTIONS:
break
with open(filename) as f:
# do smth with f
Without break:
import os
ALLOWED_EXTENSTIONS = {".bat", ".exe"}
extension = None
while extension not in ALLOWED_EXTENSTIONS:
filename = input("Enter file you like to open: ")
extension = os.path.splitext(filename)[1]
with open(filename) as f:
# do smth with f
Without break and without any imports:
ALLOWED_EXTENSTIONS = (".bat", ".exe")
filename = ""
while not filename.endswith(ALLOWED_EXTENSTIONS):
filename = input("Enter file you like to open: ")
with open(filename) as f:
# do smth with f
Without break and without any imports and without endswith():
ALLOWED_EXTENSTIONS = {"bat", "exe"}
filename = ""
while filename.rsplit(".",1)[-1] not in ALLOWED_EXTENSTIONS:
filename = input("Enter file you like to open: ")
with open(filename) as f:
# do smth with f
You don't need a loop
def ask_exe(prompt='Executable file name? '):
name = input(prompt)
if name[-4:] in {'.exe', '.bat'}: return name
return ask_exe(prompt='The name has to end in ".exe" or ".bat", please retry: ')
[no breaks, no imports, almost no code...]
As noted by ShadowRanger my code, that uses set notation for the membership test, is suboptimal for Python versions prior to 3.2. For these older versions using a tuple avoids computing the set at runtime, each and every time the function is executed.
...
# for python < 3.2
if name[-4:] in ('.exe', '.bat'): return name
...

inputting a words.txt file python 3

I am stuck why the words.txt is not showing the full grid, below is the tasks i must carry out:
write code to prompt the user for a filename, and attempt to open the file whose name is supplied. If the file cannot be opened the user should be asked to supply another filename; this should continue until a file has been successfully opened.
The file will contain on each line a row from the words grid. Write code to read, in turn, each line of the file, remove the newline character and append the resulting string to a list of strings.After the input is complete the grid should be displayed on the screen.
Below is the code i have carried out so far, any help would be appreciated:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
except IOError as e:
print ("File Does Not Exist")
Note: Always avoid using variable names like file, list as they are built in python types
while True:
filename = raw_input(' filename: ')
try:
lines = [line.strip() for line in open(filename)]
print lines
break
except IOError as e:
print 'No file found'
continue
The below implementation should work:
# loop
while(True):
# don't use name 'file', it's a data type
the_file = raw_input("Enter a filename: ")
try:
with open(the_file) as a:
x = [line.strip() for line in a]
# I think you meant to print x, not a
print(x)
break
except IOError as e:
print("File Does Not Exist")
You need a while loop?
while True:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
break
except IOError:
pass
This will keep asking untill a valid file is provided.

Categories

Resources