word counting in python in file with spaces in name - python

Here is my code
fname = input("Enter file name: ")
word=input("Enter word to be searched:")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
I am running it on windows if the file name is having spaces in it
such as "some file xyz.txt"
then upon running the above code I am getting error
Enter file name: "some file xyz.txt"
Enter word to be searched:cs
Traceback (most recent call last):
File "D:/folder1/folder2/folder3/some file xyz.txt", line 5, in <module>
with open(fname, 'r') as f:
OSError: [Errno 22] Invalid argument: '"some file xyz.txt"'
>>>
How should I enter correct file name with spaces or the code itself is wrong?

Just enter the file name without quotes. Python treats your input as a whole string.

Related

I am unable to create multiple files with this code, what is wrong?

So I'm trying to write a program that takes names from a list and adds it to a letter. A text file is created for each name for the letter however the code seems to stop working at that point.
letter = []
names = []
file = open("Input/Letters/starting_letter.txt", "r")
letter = file.readlines()
file.close()
name1 = open("Input/Names/invited_names.txt", "r")
names = name1.readlines()
name1.close()
for name in names:
create_letter = open(f"{name}.txt", "w")
for line in letter:
line = line.replace("[name],", f"{name},")
create_letter.write(line)
create_letter.close()
I get the error message
Traceback (most recent call last):
File "C:\Users\Default User\PycharmProjects\Mail Merge Project Start\main.py", line 10, in <module>
create_letter = open(f"{name}.txt", "w")
OSError: [Errno 22] Invalid argument: 'Aang\n.txt'
Is there a problem with the way I am creating the files?
You can't have newlines in your file name. It is invalid in your OS/filesystem.
Remove them with:
open(f"{name.strip()}.txt", "w")
Or:
open(f"{name.replace('\n', '')}.txt", "w")

I need to print the specific part of a line in a txt file

I have this text file that reads ,,Janitors, 3,, ,,Programers, 4,, and ,,Secretaries, 1,, and all of these are on different lines. I need to print out Janitor seperate from the number 3, and this has to work for basicaly any word and number combo. This is the code I came up with and, of course, it doesnt work. It says ,,substring not found,,
File = open("Jobs.txt", "r")
Beg_line = 1
for lines in File:
Line = str(File.readline(Beg_line))
Line = Line.strip('\n')
print(Line[0: Line.index(',')])
Beg_line = Beg_line + 1
File.close()
Try running the following code:
file = open("Jobs.txt", "r")
lines = file.read().split('\n')
for line in lines:
print(line.split(' ')[0])
file.close()
This will give the following output:
Janitors
Programers
Secretaries

Open an image file when the path is made from os.path.join

I use two different scripts. In the first one, there is something like this:
f = open(filename, 'r')
file, file_ext = os.path.splitext(filename)
thumb=open(file +"_thumb.txt","w")
for line in f:
array = line.split(',')
a = str(array[0])
t=a[11:14]+ "\\" + a[15:19] + "\\" + (a[11:])+".jpg" +"\n"
thumb.write(t)
thumb.close()
In the second one:
Dirname = str(self.lneDirIn1.text())
f=open(file +"_thumb.txt","r")
for line in f:
line=str(line)
print(line)
cl_img_path=os.path.normpath((os.path.join(Dirname,line)))
print(cl_img_path)
cl_img=Image.open(str(cl_img_path))
When I run the second one, there is an error because os.path.join actually joins the "\n" of the line, so cl_img cannot be opened. However, When I print the "line" alone, it doesn't display the '\n'
Here is the error:
Traceback (most recent call last):
File "./midas/mds_central_line_thumbs.py", line 118, in pbtOKClicked
self.process()
File "./midas/mds_central_line_thumbs.py", line 105, in process
cl_img=Image.open(str(cl_img_path))
File "C:\0adtoolsv2\libs\Python27\lib\site-packages\PIL\Image.py", line 1952, in open
fp = __builtin__.open(fp, "rb")
IOError: [Errno 22] invalid mode ('rb') or filename: 'k:\\SBU_3\\USA\\PIO2015\\04-TEST-SAMPLES\\USCASFX1608\\D16MMDD\\B3\\Images\\051\\0151\\051_0151_00021466.jpg\n'
I'd like that my second script doesn't take the "\n" (necessary in the first script) into account when opening the file
Thank you very much, Guillaume.
What about stripping the "\n" when reading the line?
line=str(line).strip()
Or when joining the path?
cl_img_path=os.path.normpath((os.path.join(Dirname, line.strip())))
Or when openning the image?
cl_img=Image.open(str(cl_img_path).strip())
You could simply use :
lines = file.read().splitlines()
for line in lines :
print line #Wouhou, no \n

reading last line of txt file in python and change it into variable to make calculation

td = 'date of transaction.txt'
tf = 'current balance.txt'
tr = 'transaction record.txt'
for line in open(tf):pass
for line2 in open(td):pass
for line3 in open(tr):pass
print line2,line,line3
"""
so call recall back last record
"""
rd=raw_input('\ndate of transaction: ')
print "Choose a type of transaction to proceed... \n\tA.Withdrawal \n\tB.Deposit \n\tC.Cancel & exit"
slc=raw_input('type of transaction: ')
i=1
while (i>0):
if slc=="A" or slc=="B" or slc=="C":
i=0
else:
i=i+1
slc=raw_input('invalid selection, please choose again...(A/B/C): ')
if slc=="A":
rr=input('\namount of transaction: ')
Line_len = 10 # or however long a line is, since in my example they all looked the same
SEEK_END = 2
file = open(tf, "r")
file.seek(-Line_len, SEEK_END)
a = int(str(file.read(Line_len)).split(" ")[0].strip())
rf=a-rr
f1=open(tf, 'a+')
f1.write('\n'+rf)
f1.close()
d1=open(td, 'a+')
d1.write('\n'+rd)
d1.close
r1=open(tr, 'a+')
r1.write('\n-'+rr)
r1.close
else:
print 'later'
above is my code, the function is to get data(last line) from txt file and read it, get new data and write it to the txt file again by creating new line.
my txt file(current balance.txt) should look like this:
2894.00
2694.00
but when i try to use the last line which is 2694.00 to do calculation(rf=a-rr), it failed returning this error:
Traceback (most recent call last):
File "C:\Python27\acc.py", line 27, in <module>
file.seek(-Line_len, SEEK_END)
IOError: [Errno 22] Invalid argument
else if i use this code:
for line in open(tf):
pass
a = line
rf=a-rr
it return this error:
Traceback (most recent call last):
File "C:\Python27\acc.py", line 27, in <module>
rf=a-rr
TypeError: unsupported operand type(s) for -: 'str' and 'int'
I seriously have no idea why...please help me...
To obtain last line of the file, you can simple do
with open('my_file.txt') as file:
last_line = file.readlines()[-1]
#last_line is a string value pointing to last line, to convert it into float, you can do
number = float(last_line.strip('\n').strip(' '))
The function input is giving you a string. Try doing:
rf=a-float(rr)

Adding to user input in python

I'm trying to have the use enter an input for a file name, what I would like to do is just have the user type in the name of the file without the extension. Since the only applicable file will be a .txt file it seems redundant to have the user type the extension, so I would like to add the file extension with the code this is what I have so far:
def create_bills(filename, capacity):
f = open(filename)
mytable = mkHashTable(capacity)
for line in f:
txt = line.strip().split(' $')
person = Person(txt[0], txt[1])
if not person.name in keys(mytable):
mytable = put(mytable, person.name, person.bill)
elif person.name in keys(mytable):
index = indexOf(mytable, person.name)
else:
pass
def main():
capacity = int(input("Size of Hashtable: "))
file = input("Enter file to be read: ")
filename = (file +'.txt')
create_bills(filename, capacity)
I am unsure of how to actually approach this problem and add the .txt to the user input.
Example:
Please enter a file name:
help
.... help.txt
error:
Traceback (most recent call last):
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 30, in <module>
main()
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 28, in main
create_bills(filename, capacity)
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 12, in create_bills
f = open(filename, '.txt')
ValueError: invalid mode: '.txt'
In main you are already adding .txt to the file name entered by the user. You do not need to add it again in the open call in create_bills().

Categories

Resources