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


Messages In This Thread
File Read Issue - by Blade2021 - Aug-06-2018, 02:46 PM
RE: File Read Issue - by Larz60+ - Aug-06-2018, 03:24 PM
RE: File Read Issue - by Blade2021 - Aug-06-2018, 03:51 PM
RE: File Read Issue - by Blade2021 - Aug-06-2018, 04:52 PM
RE: File Read Issue - by Larz60+ - Aug-06-2018, 10:46 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Connecting to Remote Server to read contents of a file ChaitanyaSharma 1 288 May-03-2024, 07:23 AM
Last Post: Pedroski55
  Recommended way to read/create PDF file? Winfried 3 2,983 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,626 Nov-09-2023, 10:56 AM
Last Post: mg24
  read file txt on my pc to telegram bot api Tupa 0 1,185 Jul-06-2023, 01:52 AM
Last Post: Tupa
  parse/read from file seperated by dots giovanne 5 1,172 Jun-26-2023, 12:26 PM
Last Post: DeaD_EyE
  Formatting a date time string read from a csv file DosAtPython 5 1,432 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  How do I read and write a binary file in Python? blackears 6 7,330 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Read csv file with inconsistent delimiter gracenz 2 1,254 Mar-27-2023, 08:59 PM
Last Post: deanhystad
  Read text file, modify it then write back Pavel_47 5 1,716 Feb-18-2023, 02:49 PM
Last Post: deanhystad
  Correctly read a malformed CSV file data klllmmm 2 2,084 Jan-25-2023, 04:12 PM
Last Post: klllmmm

Forum Jump:

User Panel Messages

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