Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
File Read Issue
#1
I'm having issues getting the results i'm looking for (obviously...) I am trying to read a text file, then parse it looking for a string, If it sees that string replace text on the NEXT line. This is what I have so far:

import fileinput
import sys

x = 0
value = "car"

with fileinput.input(files="testfile.txt") as file:
    for line in file:
        if x == 1:
            line = line.replace("car", "truck")
            sys.stdout.write(line)
            print("Triggered")
            x = 0
        if value in line:
            x = 1
            print("Activated")

fileinput.close()
My textfile has the following: (just as a test)
Output:
This is line 1 This is line 2 Check Changes apple Apricot grape car car truck
Am I going about this the wrong way or am I close just missing something?
Reply
#2
do you actually want to insert a new line into the file?

right now, you read a line and if 'car' is in that line, you leave it alone, read the next line, which may or may not contain 'car', and replace 'car' if found in that line. The original line is not modified.
is this what you want to do?

If this is homework, could you just post the assignment?
Reply
#3
(Aug-06-2018, 03:24 PM)Larz60+ Wrote: do you actually want to insert a new line into the file?

right now, you read a line and if 'car' is in that line, you leave it alone, read the next line, which may or may not contain 'car', and replace 'car' if found in that line. The original line is not modified.
is this what you want to do?

If this is homework, could you just post the assignment?

No homework sadly, just a personal project working with text files. Yes, you are correct. I will change it to append or replace after I have a better starter to work with. Right now I just need something to give me a base framework to work with.

Only append the next line, No additions to line numbers. I tried using the fileinput.lineno() function but i'm not getting any better results.

I'll try to describe a better situation. If the text file consist of the following:
Apple
Pear
Apple
Apple
Grape
Current code:
import fileinput
import sys

x = 0
y = 0
value = "Pear"

with fileinput.input(files="testfile.txt", backup="test.bak",inplace=1) as file:
    for line in file:
        print(line, end='')
        if value in line:
            y = file.lineno()+1
            print(y)
        if file.lineno() == y:
            print("Line:"+line, end='')
            line = line.replace("Apple", "Orange")
            sys.stdout.write(line)
            print("Triggered", end='')

fileinput.close()
I want to ONLY change the line followed by "Pear" instead of changing every line that has apple in it. Hope that clarifies a bit.

Thank you in advance

EDIT:
If I'm thinking correctly on this I just need a way to keep the lines of the file while its parsing through it. When I run that code it erases everything but the last line. If I can get past that then I think I should be close to what I need.
Reply
#4
I got it. Of course it was right in front of me I just had to realize what it was doing. So instead of it only writing a line to the file if it saw the trigger. It writes to the file every time and only replaces what it writes if triggered. Took me a bit to finally realize this but hey, it works right?

For any future finders of this post this is the code I ended up with.

Python file:
import fileinput
import sys

x = 0
y = 0
value = "Pear"

with fileinput.input(files="testfile.txt", backup="test.bak", inplace=1) as file:
    for line in file:
        if value in line:
            y = file.filelineno()+1
        if (file.filelineno() == y) and ("Apple" in line):
            line = line.replace("Apple", "Orange")
        sys.stdout.write(line)

fileinput.close()
Testfile.txt:
Apple
Orange
Pear
Apple
Apple
Grape
Pear
Orange
Output:
Apple Orange Pear Orange Apple Grape Pear Orange
Reply
#5
here's how I would do it:
def replace_text(infile, outfile, replace_this, with_this):
    with open(infile, 'r') as f_in, open(outfile, 'w') as f_out:
        for line in f_in:
            if replace_this in line:
                line = line.replace(replace_this, with_this)
            f_out.write(line)

def testit():
    replace_text('testfile.txt', 'testfile_new.txt', 'Apple', 'Orange')


if __name__ == '__main__':
    testit()
testfile.txt:
Output:
Apple Pear Apple Apple Grape
testfile_new.txt
Output:
Orange Pear Orange Orange Grape
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to read a file as binary or hex "string" so that I can do regex search? tatahuft 3 1,139 Dec-19-2024, 11:57 AM
Last Post: snippsat
  Read TXT file in Pandas and save to Parquet zinho 2 1,274 Sep-15-2024, 06:14 PM
Last Post: zinho
  Pycharm can't read file Genericgamemaker 5 1,602 Jul-24-2024, 08:10 PM
Last Post: deanhystad
  Python is unable to read file Genericgamemaker 13 3,805 Jul-19-2024, 06:42 PM
Last Post: snippsat
  Connecting to Remote Server to read contents of a file ChaitanyaSharma 1 3,333 May-03-2024, 07:23 AM
Last Post: Pedroski55
  Recommended way to read/create PDF file? Winfried 3 4,824 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 3,881 Nov-09-2023, 10:56 AM
Last Post: mg24
  read file txt on my pc to telegram bot api Tupa 0 2,635 Jul-06-2023, 01:52 AM
Last Post: Tupa
  parse/read from file seperated by dots giovanne 5 2,257 Jun-26-2023, 12:26 PM
Last Post: DeaD_EyE
  Formatting a date time string read from a csv file DosAtPython 5 5,060 Jun-19-2023, 02:12 PM
Last Post: DosAtPython

Forum Jump:

User Panel Messages

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