worrchi
worrchi

Reputation: 1

Python changing part of each line in a file

I am learning python and I am trying to write a code that allows me to read in a file, then change a portion of each line in a text file, and the output is written to the file.

Each line in the file has different years and information in it.

What I have so far is:

filein = input('file.txt', 'r')  

for line in filein:
    str = "1984 - 2000" 
        print str.replace("1984 - 2000", "1970 - 2010")

file.close()

When I try this I get this error "SyntaxError: multiple statements found while compiling a single statement"

How can I fix/ improve this code?

Upvotes: 0

Views: 75

Answers (2)

user2884344
user2884344

Reputation: 205

First of all you have to put parenthesis around what your printing. Also change str to line and 1984-2000 to str. Like this:

print (line.replace(str, "1970 - 2010"))

Upvotes: 0

JoeC
JoeC

Reputation: 1850

I believe what you are looking for is

filein = open('file.txt', 'r')
lines = filein.read()

for line in lines:
    str = "1984 - 2000" 
    print (line.replace(str, "1970 - 2010"))

filein.close()

Upvotes: 2

Related Questions