1

I have a file with few thousand lines like this:

0.5  AA
2.7 AA
45.2 AA
567.1 CC
667.5 AA 
4456 AA
1005.2 CC

I want add comment signs "//" at the beginning of each line contains string "CC".

I have code like this:

import fileinput

file_name = input("file path: ")

for line in fileinput.FileInput(file_name, inplace=1):
    if 'CC' in line:
        line = line.rstrip()
        line = line.replace(line,'// '+line)
    print (line)

Everything works fine but the file looks like that after execute the code:

0.5  AA

2.7 AA
    
45.2 AA
    
// 567.1 CC
667.5 AA
    
4456 AA
    
// 1005.2 CC

Why after execute the code i have the new line spaces after line without changes? How I can remove this? Second question is: How i can save this file as a new file?

Summarizing: I need to write code which in a txt file will add "//" to the beginning of each line containing "CC" and save it as a new file.

1
  • Each line ends with \n. You need to rstrip() every line. Commented Oct 5, 2020 at 15:41

4 Answers 4

3

This solution works well, what you think about it ?

filepath = input("original file :")
filepath2 = input("result file : ")

with open(filepath, "r") as f, open(filepath2, "w") as f2:
    for line in f:
        f2.write(line if not 'CC' in line else "//" + line)
Sign up to request clarification or add additional context in comments.

Comments

0

It seems like a character issue in your input file. Maybe .strip() instead of .rstrip() will work better. .rstrip() only removes whitespaces at the right of the string while .strip() removes them left and right. Something like this should work:

inputFile = open('data.txt', 'r')
outputFile = open('outputFile.txt', 'w')

for line in inputFile:

    outputLine = line.strip() + '\n'
    if 'CC' in line:
        outputLine = '//' +  outputLine
    outputFile.write(outputLine)
 
inputFile.close()
outputFile.close()

Comments

0

The extra new lines is due to the '\n' characters present already in lines of the file, you can prevent that by changing to

print(line, end='')

I dont know why you prefer file input module for reading files, becuase I find the default method open to be quite satisfactory as you can read and write textfiles, binaryfiles, etc... As for your question:

with open(file_name, 'w') as file:
    file.write(data)

Comments

0

here is a solution :

p="name_of_original_file.txt"
file=open(p,"r")
s=file.read()
file.close() 

new_s=""
for line in s.splitlines():
    if 'CC' not in line:
        new_s+=line+"\n"
    if 'CC' in line:
        new_s+='// '+line+"\n"
    print (line)

p="name_of_new_file.txt"
file=open(p,"w")
file.write(new_s)
file.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.