Can't Take in Multiple Text File - python

Hello this is a problem I am having. The following program doesn't allow me to take in multiple outplane data but it allow to take in multiple in plane data according to the function in call_Controller. Is there something wrong with the program?
you can try by creating this 4 text file in a folder.
run the program and press Clt to take in both hello.txt and bye.txt
follow by hello1.txt and bye1.txt and you will know the error
somebody please help me with this problem..
hello.txt | hello1.txt
bye.txt | bye1.txt
Error Message:
Traceback (most recent call last):
File "C:\ProjectMAPG\TRYPYTHON\src\OldPythonTry.py", line 100, in <module>
Name = call_Controller(file_path_IP, InputfilesListOoplane)
File "C:\ProjectMAPG\TRYPYTHON\src\OldPythonTry.py", line 67, in call_Controller
with open(InputfilesListOoplane) as f1:
IOError: [Errno 22] invalid mode ('r') or filename: u'C:/Users/zhenhui/Desktop/bye1.txt C:/Users/zhenhui/Desktop/hello1.txt'
function to extract the file name:
def extractFilename(FileNameOnly):
stripText = string.split(FileNameOnly, " ")
FileName = stripText[0]
return (FileName)
pass
I think the problem is here. As the outplane have doesn't allow me to take in multiple folder:
def call_Controller(file_path_Inplane, InputfilesListOoplane):
FileNameOnlyIP = splitext(basename(file_path_Inplane))[0]
Name = extractFilename(FileNameOnlyIP)
#Extract raw inplane
with open(file_path_Inplane) as f:
f.readline()
#Extract raw outplane
with open(InputfilesListOoplane) as f1:
f1.readline()
return Name
Start of the program:
if __name__ == '__main__': #start of program
win = Tk.Tk() #Open up connection and declare button and label
master=win
initial_dir = "C:\VSM"
#Create Directory if its not there
try:
if not os.path.exists(newDirRH[0]):os.makedirs(newDirRH)
except: pass
#Open to select multiple files for files
file_path_Inplane= tkFileDialog.askopenfilename(initialdir=initial_dir, title="Select VSM Files", multiple =1)
if file_path_Inplane != "": pass
else:
print "You didn't open anything!"
InputfilesListInplane = win.tk.splitlist(file_path_Inplane)
#Open to select multiple files for outplane
file_path_Ooplane = tkFileDialog.askopenfilename(initialdir=initial_dir, title="Select Out of Plane Files", multiple = 1)
if file_path_Ooplane != "":
pass
else:
print "You didn't open anything!"
InputfilesListOoplane = file_path_Ooplane#master.tk.splitlist(file_path_Ooplane)
for file_path_IP in InputfilesListInplane:
Name = call_Controller(file_path_IP, InputfilesListOoplane)
print "Done " + Name

I'm not sure what "in multiple outplane data" might be but the error message explains quite clearly:
'C:/Users/zhenhui/Desktop/bye1.txt C:/Users/zhenhui/Desktop/hello1.txt'
is not a valid file name. For me, this looks like two file names that you appended with a space between them.
When you open files, neither Python nor the OS will try to read your mind. Use a single file name per operation.

Prolem here:
IOError: [Errno 22] invalid mode ('r') or filename: u'C:/Users/zhenhui/Desktop/bye1.txt C:/Users/zhenhui/Desktop/hello1.txt'
Check correct place of delivery your path.
Next potential pronlem here initial_dir = "C:\VSM". Must initial_dir = "C:\\VSM" or initial_dir = "C:/VSM". Furthermore use path-related functions from os.path module.

Related

read/write a file input and insert a string

I need to write function which given a text file object open in read and write mode and a string, inserts the text of the string in the file at the current read/write position. In other words, the function writes the string in the file without overwriting the rest of it. When exiting the function, the new read/write position has to be exactly at the end of the newly inserted string.
The algorithm is simple; the function needs to:
read the content of the file starting at the current read/write position
write the given string at the same position step 1 started
write the content read at step 1. at the position where step 2. ended
reposition the read/write cursor at the same position step2. ended (and step 3. started)
If the argument file object is not readable or writable, the function should print a message and return immediately without changing anything.
This can be achieved by using the methods file object methods readable() and writable().
In the main script:
1- prompt the user for a filename
2- open the file in read-write mode. If the file is not found, print a message and exit the program
3- insert the filename as the first line of the file followed by an empty line
4- insert a line number and a space, at the beginning of each line of the original text.
I'm very confused on how to write the function and main body.
so far I only have
def openFile(fileToread):
print(file.read())
givefile = input("enter a file name: ")
try:
file = open(givefile, "r+")
readWriteFile = openFile(file)
except FileNotFoundError:
print("File does not exist")
exit(1)
print(givefile, "\n")
which is not a lot.
I need an output like this:
twinkle.txt
1 Twinkle, twinkle, little bat!
2 How I wonder what you're at!
3 Up above the world you fly,
4 Like a teatray in the sky.
the file used is a simple .txt file with the twinkle twinkle song
How can I do this?
Basic solution
give_file = input("enter a file name: ")
def open_file(file):
return file.read()
def save_file(file, content):
file.write(content)
try:
# Use this to get the data of the file
with open(give_file, "r") as fd:
file_content = open_file(fd)
except FileNotFoundError:
print("File does not exist")
exit(1)
# change the data
new_content = f'{give_file}\n\n{file_content}'
try:
# save the data
with open(give_file, "w") as fd:
save_file(fd, new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
This should give you the expected result.
I asked about the r+ and how to use it in this case. I got this answer:
reset the cursor to 0 should do the trick
my_fabulous_useless_string = 'POUET'
with open(path, 'r+') as fd:
content = fd.read()
fd.seek(0)
fd.write(f'{my_fabulous_useless_string}\n{content}')
so with your code it's:
give_file = input("enter a file name: ")
def open_file(file):
return file.read()
def save_file(file, content):
file.write(content)
try:
# Use this to get the data of the file
with open(give_file, "+r") as fd:
file_content = open_file(fd)
new_content = f'{give_file}\n\n{file_content}'
fd.seek(0)
save_file(fd, new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
A suggestion
Don't use function, it hide the fact that a method is used with some side-effects (move the cursor).
Instead, call the method directly, this is better:
give_file = input("enter a file name: ")
try:
# Use this to get the data of the file
with open(give_file, "+r") as fd:
file_content = fd.read()
new_content = f'{give_file}\n\n{file_content}'
fd.seek(0)
fd.write(new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
Or, with the basic solution and functions
def open_file(path):
with open(path, "r") as fd:
return fd.read()
def save_file(path, content):
with open(path, 'w') as fd:
fd.write(content)
# get file_name
file_name = input("enter a file name: ")
try:
# Use this to get the data of the file
file_content = open_file(file_name)
except FileNotFoundError:
print("File does not exist")
exit(1)
# change the data
new_content = f'{file_name}\n\n{file_content}'
# save the data
save_file(file_name, new_content)

How to prompt user that asks a user for a file name?

I am going through Intro to Programming so basic stuff here, I have an assignment to "write a program that asks a user for a file name and then displays the first 5 lines of the file," I just can't figure out how to use the input command in this situation and then transfer to open()
Edit: Sorry here is a code snippet I had, I just don't get how to apply input from here.
def main():
#This function writes to the testFile.docx file
outfile = open('testFile.docx', 'w')
outfile.write('Hello World\n')
outfile.write('It is raining outside\n')
outfile.write('Ashley is sick\n')
outfile.write('My dogs name is Bailey\n')
outfile.write('My cats name is Remi\n')
outfile.write('Spam Eggs and Spam\n')
outfile.close()
infile = open('testFile.docx', 'r')
testFileContent = infile.read()
infile.close()
print(testFileContent)
main()
First, we ask for a filename. Then we use the try clause, which checks whether the file exists. If it does it will print 5 lines. If it does not, it will print No such a file found!
x = input('Enter a file name')
try:
with open(x) as f:
data = f.readlines()
for i in range(5):
print(data[i])
except:
print('No such a file found!')
Using a simple function,
def hello_user():
user_input = input('Enter file name: ')
try:
with open(user_input, 'r') as f:
data = f.readlines()
data = data[:5]
for o in data:
print(o.strip())
except FileNotFoundError:
print('Not found ')
hello_user()
It asks for a file name
If the file exists in the same directory the script is running, it opens the file and read each lines (white lines inclusive)
We select only the first 5 lines
We iterate through the list and remove the extra whitespace character(e.g \n).
If the file was not found, we catch the exception.
input() is used to receive input from the user. Once we recieve the input, we use the open() method to read the file in read mode.
def main():
file = input("Please enter a file name")
with open(file, 'r') as f:
lines = f.readlines()
print(lines[:5])
The with statement makes sure that it closes the file automatically without explicitly calling f.close()
The method f.readlines() returns an array containing the lines in the file.
The print() statement prints the first 5 lines of the file.

I am prompted with an error message when I run it

I have this program working how it should be but there is 1 small problem that I'm having and I really don't know what to do about it. I feel like to fix the problem I have to reformat my entire program. In the very beginning of the while loop. I created a with statement that executes what the program is supposed to do. The program opens a file, reads it, and outputs how many unique words there are in a text file. The with statement works, but now the error checking past the with statement does not execute and I'm prompted with an error. When you input a file that does not exist it is supposed to prompt the user saying "The file (filename) does not exist!" But that code past the with statement is no longer executed and I'm prompted with a FileNotFoundError.
def FileCheck(fn):
try:
open(fn, "r")
return 1
except IOError:
print("The file " + filename + " was not found!")
return 0
loop = 'y'
while loop == 'y':
filename = input("Enter the name of the file you wish to process?: ")
with open(filename, "r") as file:
lines = file.read().splitlines()
uniques = set()
for line in lines:
uniques = set(line.split())
print("There are " + str(len(uniques)) + " unique words in " + filename + ".")
if FileCheck(filename) == 1:
loop = 'n'
else:
exit_or_continue = input("Enter the name of the file you wish to process or type exit to quit: ")
if exit_or_continue == 'exit':
print("Thanks for using the program!")
loop = 'n'
else:
break
Here is the error message when I input a file that does not exist
Enter the name of the file you wish to process?: aonsd.txt
Traceback (most recent call last):
File "C:/Users/C/PycharmProjects", line 21, in <module>
with open(filename, "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'aonsd.txt'
Your problem is a logic problem here:
filename = input("Enter the name of the file you wish to process?: ")
with open(filename, "r") as file:
...
if FileCheck(filename) == 1:
You very clearly input a file name and then, without bothering to check its existence, try to open it. You don't check until you've finished reading the file.
The logic you expressed in your written description suggests that you want
filename = input("Enter the name of the file you wish to process?: ")
if FileCheck(filename):
with open(filename, "r") as file:
...

How to use ask open file name with open function then take that file into another function?

I'm making a program that takes two file comparing them then find the percentage of similarity,now I'm having hard time to take the file name THEN Pass IT TO open function to read it THEN PASSING THE DATA Generated into another function ,it shows me that error
IOError: [Errno 22] invalid mode ('r') or filename: ''
my code is
Copied_File = ''
def Click_Copy():
global Copied_File
Copied_File = tkFileDialog.askopenfilename(initialdir='C:/Users/%s' % user)
directory = os.path.split(Copied_File)[0]
return Copied_File
with open((Copied_File), 'r')as file_1:
file1_data = file_1.read()
View_copied_File.insert(0.0, file1_data)
btn_Copy = ttk.Button(text="Open Copied File",command=Click_Copy)
btn_Copy.place(x =10, y = 30, width=120, height=34)
View_copied_File= ScrolledText(Window_1, width=50, height=40,state = "normal")
View_copied_File.place(x =10, y = 70)
As #Stefans commented you, there is a problem when you tried to open the file Copied_File because by the moment you run the with open((Copied_File), 'r')as file_1:, you have Copied_File =.
This means:
with open((Copied_File), 'r')as file_1: is equal to with open('', 'r')as file_1:
You defined Click_Copy() method but you never executed it. So you need to call that method before the with statement.
To resolve your problem, you may call the method directly:
...
with open(Click_Copy(), 'r') as file_1:
...

IOError: [Errno 2] No such file or directory, even though the file is existed

I am trying to figure out why I am having such error. I ran the same exact code for another directory which contains four files and it is working just fine. This time with using another directory I am getting error this error
IOError: [Errno 2] No such file or directory:
even though the files existed. Here is the code which works fine for one directory but not the other one both directory exists and so their four files
The error at line:"with open((file_name),'r') as f:"
import sys,csv,os
d_files = {}
def Readfile(file_name):
d_files[file_name] = []
print "file_name", file_name # printing the right name
with open((file_name),'r') as f:
reader=csv.reader((f),delimiter='\t')
for row in reader:
d_files[file_name].append(row)
print
try:
folder_input = raw_input("Please enter you folder name containing 4 files: ")
except Name_Error:
pass
for root,dirs,files in os.walk(folder_input):
for file in files:
print "file",file # the right file name
pathname=os.path.join(root,file)
print "DIR: ",pathname # right directory inputted
print "Now, the file is being parsed"
Readfile(file)
print "Now, file", file, "is done parsed"
print
The user will type the path of the four files and which I tested for one directory and it worked but not for the other directory which I am 100% sure that the path is correct and the files exist.
Thanks a lot in advance
Call Readfile with pathname instead. As shown below:
import sys,csv,os
d_files = {}
def Readfile(file_name):
d_files[file_name] = []
print "file_name", file_name # printing the right name
with open((file_name),'r') as f:
reader=csv.reader((f),delimiter='\t')
for row in reader:
d_files[file_name].append(row)
print
try:
folder_input = raw_input("Please enter you folder name containing 4 files: ")
except Name_Error:
pass
for root,dirs,files in os.walk(folder_input):
for file in files:
print "file",file # the right file name
pathname=os.path.join(root,file)
print "DIR: ",pathname # right directory inputted
print "Now, the file is being parsed"
Readfile(pathname)
print "Now, file", file, "is done parsed"
print
Try the following:
import sys,csv,os
d_files = {}
def Readfile(file_name):
d_files[file_name] = []
print "file_name", file_name # printing the right name
with open(file_name,'r') as f:
reader=csv.reader((f),delimiter='\t')
for row in reader:
d_files[file_name].append(row)
print
try:
folder_input = raw_input("Please enter you folder name containing 4 files: ")
except Name_Error:
pass
for root,dirs,files in os.walk(folder_input):
for file in files:
print "file",file # the right file name
pathname=os.path.join(root,file)
print "DIR: ",pathname # right directory inputted
print "Now, the file is being parsed"
# Make sure here you type a file name under same directory
# or full path: "C:\\boot.ini" or "/etc/passwd". Also make sure the user running the script has permission for the folder.
Readfile(file)
print "Now, file", file, "is done parsed"
print

Categories