简体   繁体   中英

python fileinput if and

I want to find values in a line in a file and replace them.

When I do this:

def replace(file_name, name, original_value, new_value):
    for line in fileinput.input(file_name, inplace=1):
        if name in line:
            print(line)

I can print out each line that the 'name' appear in.

If I do the following then it DOES NOT print out the line even though the 2 values appear in the line in the file:

def replace(file_name, name, original_value, new_value):
    for line in fileinput.input(file_name, inplace=1):
        if name in line and original_value in line:
            print(line)

How do I get this to do IF AND?

//Sample line in my text file
add_argument('--look_for_this',  test)

config_name = "look_for_this"     
old = 'test'
new = 'new_value'

replace(config_file, config_name, old, new)  

I tried your code like the following and it works for me. You have to specify in more detail what the issue is!

lines = ['1. a b c', '2. c d e', '3. e f g', '4. c e']
name = 'c'
original_value = 'e'

for line in lines:
    if name in line and original_value in line:
        print(line)

Producing the following output:

2. c d e
4. c e

Which is what you would expect. Hence, I can only assume that you must have some bug in the code which either provides the name or the original_value not in the form you expect. Or the line is not in the form you expect. Eg encoding could be an issue if you look for specific byte patterns or similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM