Python Forum
Basic Python 3 Win 10 Search Txt to File Newbie
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic Python 3 Win 10 Search Txt to File Newbie
#1
Hello,
First post, but have spent hours online trying to get first usable program other than "Hello World" to work. All posted solutions found to have bugs on my setup - different Python versions(?).
Very simple for...next type algorithm with all "Basic" progs, VB, PowerBasic or batch file, but examples online don't work, so far. My first attempt to try out Python, due to all of the hoopla about its power etc.

Running Python 3.7.2 .py file from Win 10 "Desktop," I open a text file with several one line entries of credit card names. Some end with "VisaRen" indicating that I need to renew or update them.

I want an output text file of just those "Visa" flagged files. After a fairly exhaustive search, I found only one program that gives me 1 (one) result (one line of text) in an output file. I want all lines that match a search criterium.

Here is my attempt, admittedly copied from an online "expert's" example with double backslashes used instead of single backslashes as he recommended:

stringToMatch = 'VisaRen'
matchedLine = ''
 
#get line
# NOTE to self - " and \\ used for Python 3.7 instead of ' and \
with open("C:\\Users\\John\Desktop\\StuffIn.txt", "r") as file:
	for line in file:
		if stringToMatch in line:
			matchedLine = line
			break
 
#and write it to the file
with open("C:\\Users\\John\Desktop\\StuffOut.txt", "w") as file:
	file.write(line)
	#Above was (matchedLine)
	
# f = close() - ??
Any help appreciated. About to give up on Python!
Reply
#2
The break ends the first loop, so you only get one matched line. You need to store the matched lines in an array (and not break after each one), then use a for loop on the array to write each of them out to your output file.
Reply
#3
Wow - thank you for such a quick reply! That makes sense. Now, I'm 73 years old and haven't done arrays for a while, but I can look it up.

However, is there a simpler "Line Input, Write" routine until the end of file ("While Not EOF")? My list contains passwords and contacts as well from many years working IT stuff for an employer; so it is over 100 pages long.
Reply
#4
You could have one loop do both the reading and writing; this is probably better anyway if that's all you are doing.

    infile = open("C:\\Users\\John\Desktop\\StuffIn.txt", "r")
    outfile = open("C:\\Users\\John\Desktop\\StuffOut.txt", "w")
    for line in infile:
        if stringToMatch in line:
            #write it to the output file
            outfile.write(line)
    infile.close()
    outfile.close()
Reply
#5
Can write it it like this.
match = 'VisaRen'
with open('lines.txt') as f,open('new.txt', 'w') as f_out:
    for line in f:
        if match in line:
            f_out.write(line)
(Apr-18-2019, 09:05 PM)SnakeTyro Wrote: However, is there a simpler "Line Input, Write" routine until the end of file ("While Not EOF")?
Python always read to EOF,if not stop it in anyway.
So for line in f: read one line(memory effective) at time to EOF.
Reply
#6
I think I understand what you want to do. Does this code produce a result to your liking?
# some named constants here so if you want to change these values, you don't need run around
# changing a bunch of hard-coded literals.
SOURCE_FILE_PATH = "C:\\Users\\John\Desktop\\StuffIn.txt"
DESTINATION_FILE_PATH = "C:\\Users\\John\Desktop\\StuffOut.txt"
SEARCH_TARGET = 'VisaRen'

# You want all the strings that contain your search target in your destination file, so we
# use a list and append everything to it.
matchedStrList = []
with open(SOURCE_FILE_PATH, "r") as f:
    # The readlines method returns a list with all the lines in the file, sans trailing 
    # newlines.
    for line in f.readlines():
        # list.append takes a single object as a parameter and puts it on the end of the list.
        if SEARCH_TARGET in line: matchedStrList.append(line)

with open(DESTINATION_FILE_PATH, "w") as f:
    # enumerate returns the tuple (index, value) where index is the index within the iterable
    # where the value appears. Using this syntax, we can unpack these two values into separate
    # variables
    for index, line in enumerate(matchedStrList):
        if index < len(matchedStrList) - 1:
            f.write(line + "\n")
        else:
            # Write the last item to the file without a trailing newline. (You can get rid of
            # this functionality if you want.)
            f.write(line)
I hope this solution helps. Python is for the most part, very well documented and there are a lot of tutorials available on many platforms. Don't be afraid to look around.
Reply
#7
Thank you, gentlemen or gentlepersons, for the immediate and effective help.

The program now works, and I can begin to see why this language is so successful, even for using it at home. Very concise.

keames, I also appreciate your extended and heavily documented code so that I can start to pick up some of the gist and structure of python. I will be studying this, have two Python books on Kindle and two hardcopy books on order. Hopefully, I can help some newbie like me in the future as a "pay it forward" type thing.

Have some family chores now; very appreciative of the quick help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  very newbie problem on text file zapad 2 209 Apr-12-2024, 06:50 PM
Last Post: zapad
  Basic binary search algorithm - using a while loop Drone4four 1 361 Jan-22-2024, 06:34 PM
Last Post: deanhystad
  Search Excel File with a list of values huzzug 4 1,241 Nov-03-2023, 05:35 PM
Last Post: huzzug
  Search for multiple unknown 3 (2) Byte combinations in a file. lastyle 7 1,330 Aug-14-2023, 02:28 AM
Last Post: deanhystad
  search file by regex SamLiu 1 912 Feb-23-2023, 01:19 PM
Last Post: deanhystad
  If function is false search next file mattbatt84 2 1,151 Sep-04-2022, 01:56 PM
Last Post: deanhystad
  Python newbie laleebee 2 1,321 May-24-2022, 01:39 PM
Last Post: laleebee
  fuzzywuzzy search string in text file marfer 9 4,575 Aug-03-2021, 02:41 AM
Last Post: deanhystad
  Cloning a directory and using a .CSV file as a reference to search and replace bg25lam 2 2,135 May-31-2021, 07:00 AM
Last Post: bowlofred
  Basic python Natters10 3 3,091 Nov-29-2020, 07:04 AM
Last Post: Love2code

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020