0

I am trying to lookup a value in my csv file and if I find it, write back a value at the end of its row. For example, if the csv looks like this:

 #   A  B 
111  1
112  0
113  0
114  1

and I lookup 111 and want to write 0 in the first empty cell in its row, how can I do it?

4
  • so you want 111 1 to be like 111 1 0 or 111 0? And each line will have only two values? seperated by space? Commented Sep 11, 2019 at 18:48
  • No No i want it to be 111 1 0, which means that the row will now have 3 values Commented Sep 11, 2019 at 18:51
  • @HamzaAhmad First empty cell: what is the separator? Tab or Space? Commented Sep 11, 2019 at 19:02
  • By the way, why are you using whitespace as the field delimiter in a CSV? Commented Sep 13, 2019 at 14:12

3 Answers 3

1

There is no way to insert data in the middle of a file. Writing to the middle of a file will overwrite the data at that position. Instead:

  • open the file in read mode
  • read all the data in the file
  • close the file
  • reopen the file in write mode
  • write the first few lines
  • write your extra data
  • write the rest of the original data

an example:

with open('test.csv') as f:
l = f.readlines()

l[4] += '0'
with open('test2.csv', 'w') as f:
    f.writelines(l)
Sign up to request clarification or add additional context in comments.

2 Comments

@jarmod you are right, but this will overwrite existing data in that position. I will change the answer text
As a sidenote: for very large files, instead of re-writing the first n lines, you might want to seek to the correct position. But for most moderately sized files the approach in this answer will do.
0
with open('text.csv', 'r') as f:
    rows = [x.split() for x in f]
with open('text_1.csv', 'w') as f:
    for row in rows:
        f.write(row[0] + " " + row[1])
        if row[0] == '111': # or you can check for multiple values here.
            f.write("0")
        f.write("\n")

4 Comments

The x.split() approach to parsing csv files is a bad idea. The csv format is trickier than you think. Instead it's better to use the builtin csv package.
Or: rows = [x.split() for x in open('text.csv')]
@rje Can you please explain me on why split method might fail. Don't know/encountered major issues with it. Wanted to know.
There's several reasons. One is that you might have a quoted field containing a delimiter. In that case your method might fail.
0

This will let you open, read and write to the file within a single context manager in one shot.

search_term = '112' # This is what you are looking 
                    # for at the start of the lines.
##-------------------------------------------------------##
# Define separator
sep = '\t' # Use '\t' (TAB) or " " (SPACE)
val = 0 # This is the value you want to insert 
        # at the end of the target line.
##-------------------------------------------------------##
write_to_file = False # Set this to True when 
                      # you want to write to the file.

##-------------------------------------------------------##
with open("dummy.csv","r+") as f:
    content = f.readlines()
    for i,line in enumerate(content):
        if line.startswith(search_term):
            line = line.strip() + '{}{}\n'.format(sep,val)
            content[i] = line
    if write_to_file:
        f.writelines(content)

print(''.join(content))

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.