I have a python program that is supposed to search a text file for an ID. If the Id doesn't exist in the file then the program will write it to the file.
path = "M:\\Program\\files\\"
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
for x in range(0, len(files)):
file = files[x]
file = file.split('`')
postid = file[0]
print(postid)
with open('postid.txt', 'r+') as f:
if postid in f:
print('already used')
else:
print('not used')
f.write(postid + '\r')
The code always returns that the string isn't in the file when It is. I have tried different methods of scanning the file such as using a for loop and examining each line but they haven't worked. I feel like I am missing some small detail but I cant find what I have done wrong.
The file looks like
1k2kk
302kk
2ll3d
2ll32
33lld
ect..
EDIT:
Never found out why the code wasn't working. I tried every suggestion but nothing worked. Finally gave up trying to read directly from the file and just had the program dump the file into a list and search the list for the ID instead of the file. I know this is not ideal but the ID file will probably not be very big when using the program so hopefully this will not cause issues.
Try a+ as the access mode.
with open('postid.txt', 'a+') as f:
You need to search the file line by line (or chunk by chunk but line by line is easiest):
with open('postid.txt', 'r+') as f:
for line in f.readlines():
if postid in line:
print("already used")
break
else:
print("not used")
f.write(postid + '\r')
I refactored your code, although I'm not sure how to name some of the variables.
for curr_str in files:
postid = curr_str.split('`')[0]
print(postid)
with open('postid.txt', 'a+') as f:
for line in f:
line = line.rstrip()
if postid == line:
print('found')
break
else:
print('not found')
f.write(postid)
Related
I am stuck on this revision exercise which asks to copy an input file to an output file and return the first and last letters.
def copy_file(filename):
input_file = open(filename, "r")
content = input_file.read()
content[0]
content[1]
return content[0] + content[-1]
input_file.close()
Why do I get an error message which I try get the first and last letters? And how would I copy the file to the output file?
Here is the test:
input_f = "FreeAdvice.txt"
first_last_chars = copy_file(input_f)
print(first_last_chars)
print_content('cure737.txt')
Error Message:
FileNotFoundError: [Errno 2] No such file or directory: 'hjac737(my username).txt'
All the code after a return statement is never executed, a proper code editor would highlight it to you, so I recommend you use one. So the file was never closed. A good practice is to use a context manager for that : it will automatically call close for you, even in case of an exception, when you exit the scope (indentation level).
The code you provided also miss to write the file content, which may be causing the error you reported.
I explicitely used the "rt" (and "wt") mode for the files (althought they are defaults), because we want the first and last character of the file, so it supports Unicode (any character, not just ASCII).
def copy_file(filename):
with open(filename, "rt") as input_file:
content = input_file.read()
print(input_file.closed) # True
my_username = "LENORMJU"
output_file_name = my_username + ".txt"
with open(output_file_name, "wt") as output_file:
output_file.write(content)
print(output_file.closed) # True
# last: return the result
return content[0] + content[-1]
print(copy_file("so67730842.py"))
When I run this script (on itself), the file is copied and I get the output d) which is correct.
Please help I need python to compare text line(s) to words like this.
with open('textfile', 'r') as f:
contents = f.readlines()
print(f_contents)
if f_contents=="a":
print("text")
I also would need it to, read a certain line, and compare that line. But when I run this program it does not do anything no error messages, nor does it print text. Also
How do you get python to write in just line 1? When I try to do it for some reason, it combines both words together can someone help thank you!
what is f_contents it's supposed to be just print(contents)after reading in each line and storing it to contents. Hope that helps :)
An example of reading a file content:
with open("criticaldocuments.txt", "r") as f:
for line in f:
print(line)
#prints all the lines in this file
#allows the user to iterate over the file line by line
OR what you want is something like this using readlines():
with open("criticaldocuments.txt", "r") as f:
contents = f.readlines()
#readlines() will store each and every line into var contents
if contents == None:
print("No lines were stored, file execution failed most likely")
elif contents == "Password is Password":
print("We cracked it")
else:
print(contents)
# this returns all the lines if no matches
Note:
contents = f.readlines()
Can be done like this too:
for line in f.readlines():
#this eliminates the ambiguity of what 'contents' is doing
#and you could work through the rest of the code the same way except
#replace the contents with 'line'.
I'm writing a simple function that takes the path of a text file and returns the number of lines contained in that file.
I've made sure to set the file pointer to the beginning using file.seek(0).
def get_number_lines(file_dir):
exists = os.path.isfile(file_dir)
if (exists):
print(file_dir)
line_count = 0
read_file = open(file_dir,'r')
read_file.seek(0)
for line_num, line in enumerate(read_file.readlines()):
line_count = line_num
print(line)
read_file.close()
return (line_count + 1)
else:
print("ERROR: FILE \"" + file_dir + "\" does not exist.")
exit()
Strangely, when I try calling the function it runs ok but the output is telling me that my file is 3 lines shorter than it actually is. When I print the file lines it appears to be skipping the last 3 lines of the file and I'm not sure why.
I have tested the below code using "with open" instead of read_file.seek.
Personal opinion but it works a lot better for reading .txt files. The function will return the number of lines found in the path given to the function. If it is not a file that exists it will error and exit.
def Get_Number_Lines(file_dir):
exists = os.path.isfile(file_dir)
if (exists):
print(file_dir)
line_count = 0
with open(file_dir, 'rb') as fin:
reader = fin.readlines()
for line in reader:
line_count += 1
return line_count
else:
print("ERROR: FILE \"" + file_dir + "\" does not exist.")
exit()
Appreciate all the suggestions. So I discovered that I had a file object (in write mode) open prior to calling the get_number_lines() function i.e.
write_file = open(outputFileDir,"w+")
# do stuff
get_number_lines(outputFileDir)
I then tried closing the the file prior to calling the function which solved the issue I was having. Out of curiousity I also tried this, which works no problem:
write_file = open(outputFileDir,"w+")
# do stuff
write_file.close()
read_file.open(outputFileDir,"r")
get_number_lines(outputFileDir)
I didn't realise having two file objects (one in read, and one in write) could cause this issue.
I am a newbie with python, so kindly excuse for asking basic question.
I am trying to use the string.replace method in python and getting a weird behavior. here is what I am doing:
# passing through command line a file name
with open(sys.argv[2], 'r+') as source:
content = source.readlines()
for line in content:
line = line.replace(placeholerPattern1Replace,placeholerPattern1)
#if I am printing the line here, I am getting the correct value
source.write(line.replace(placeholerPattern1Replace,placeholerPattern1))
try:
target = open('baf_boot_flash_range_test_'+subStr +'.gpj', 'w')
for line in content:
if placeholerPattern3 in line:
print line
target.write(line.replace(placeholerPattern1, <variable>))
target.close()
When I am checking the values in the new file, then these are not replaced. I could see that the value of the source is also not changed, but the content had changed, what am I doing wrong here?
Rather do something like this -
contentList = []
with open('somefile.txt', 'r') as source:
for line in source:
contentList.append(line)
with open('somefile.txt','w') as w:
for line in contentList:
line = line.replace(stringToReplace,stringToReplaceWith)
w.write(line)
Because with will close your file after runing all the statements wrapped within it, which means the content local variable will be nil in the second loop.
You are reading from the file source and also writing to it. Don't do that. Instead, you should write to a NamedTemporaryFile and then rename it over the original file after you finish writing and close it.
Try this:
# Read the file into memory
with open(sys.argv[2], 'r') as source:
content = source.readlines()
# Fix each line
new_content = list()
for line in content:
new_content.append(line.replace(placeholerPattern1Replace, placeholerPattern1))
# Write the data to a temporary file name
with open(sys.argv[2] + '.tmp', 'w') as dest:
for line in new_content:
dest.write(line)
# Rename the temporary file to the input file name
os.rename(sys.argv[2] + '.tmp', sys.argv[2])
print "Which category would you like to view? Savory, Dessert, Cake, Soup or Drink? "
category = raw_input()
for x in os.listdir(category): print x
name = raw_input("Which recipe would wou like to view? ")
fullname = os.path.join(category, name)
f = open(fullname, "r");
print f
I am writing a program that will allow users to view the contents of .txt files saved in specific directories. When I run this code I don't get the contents and instead get a message that says this:
open file 'savory/b.txt', mode 'r' at 0x1004bd140
any ideas. I am new to python so i dont have much of an idea as to what is causing the error but i assume it is due to some missing code.
Thank you.
The return value of open is a file object (not the file contents!) .You need to call a method on your file object to actually read the file:
f = open(fullname, "r")
print f.read()
f.close()
If it's a big file you may want to iterate over the file line-by-line
f = open(fullname, "r")
for line in f:
print line
f.close()
On a side note, here's alternate syntax to you don't have to remember to call the close method:
with open(fullname, "r") as f:
for line in f:
print line