aziz
aziz

Reputation: 13

Comment some lines in a text file using python

I'm new to python and I just started learning the basics.

I'm trying to create a program that will take a file and comment (using # ) the lines that don't have anything after the equal sign.

For example,

V12 =

V13 = 3

Should be

#V12 =

V13 = 3

Thank you in advance for your help.

Upvotes: 1

Views: 5900

Answers (4)

Altronicx
Altronicx

Reputation: 171

You could also use this code to accomplish your task. The only restriction is that the empty variable is identified by no whitespace. E.g. 'v1='

MyFile=open("AFile.txt", 'r+');
newdata = []
data = MyFile.readlines()
for item in data:
    PosEquals = item.find('=')
    LenOfItem  = len(item)
    # Checks position of equals in line 
    # and also if there is anything after equal sign
    if PosEquals <> -1 and PosEquals <> LenOfItem-1:
        newdata.append(item)
    else:
        newdata.append('#'+item)
MyFile.seek(0)
MyFile.writelines(newdata)    
MyFile.close()

Upvotes: 0

snowballhg
snowballhg

Reputation: 378

For something like this I would keep it simple and read from one file and write to another.

with open('/path/to/myfile') as infile:
   with open('/path/to/output', 'w') as outfile:
      for line in infile:
         if line.rstrip().endswith('='):
             outfile.write('#' + line + '\n')
         else:
             outfile.write(line + '\n')

Upvotes: 1

Neapolitan
Neapolitan

Reputation: 2163

Here is some code that you can run like:

python comment.py < infile > outfile

comment.py:

import sys

# stdin/stdout live in sys
# "for line in file" reads each line of the file, returning the text
# of the line including the trailing newline
for line in sys.stdin:
    if line.strip().endswith('='):
        line = "#" + line
    # print command adds a trailing newline, so we have to use all but
    # the last character of our input line
    print(line[:-1])

You can get a lot fancier using the re module for regular expressions.

Given infile:

V12 = 'hello'
V23 = 'world'
V34 =

produces:

V12 = 'hello'
V23 = 'world'
#V34 =

Upvotes: 1

mattsap
mattsap

Reputation: 3806

Essentially, you'll need to read in the file. Then, check each line. If the line has something after you split on the equal sign, just output the line as is; otherwise, append a hashtag to the front and then output the line.

f = open(filename, "r")
lines = f.readlines()
f.close()

output_lines = []
for line in lines:
    if len(line.split("=")[1]) > 0:
       output_lines.append(line)
    else:
       output_lines.append("#" + line)
f = open("commented" + filename, "w")
f.write("\n".join(output_lines))
f.close()

Upvotes: 2

Related Questions