Kathryn Bradley
Kathryn Bradley

Reputation: 11

Python - replace random items in column

I'm a bit new to python so sorry if this is a basic question.

I have a file that looks something similar to this:

Zr  1   1   1
Zr  1   1   1
Zr  1   1   1
Zr  1   1   1

repeated over quite a few lines. I need to replace strings in the first column randomly with another specified string (edited for clarity), whilst keeping columns 2, 3, and 4 the same.

Any ideas how to do this? I get that I should feed the first column into an array, index each one and then randomly swap out, but I'm not sure how to proceed.

Thanks.

Kathryn :)

EDIT: FIXED.

Thanks for all of your help guys, just needed random.sample :)

Upvotes: 1

Views: 237

Answers (2)

Vaibhav Mishra
Vaibhav Mishra

Reputation: 12102

I would strongly suggest reading a python primer, the way your problem solved can be done in two steps

  1. read items from file - reference

  2. use math.random() to change random string- reference

by know how to do these points you can easily achieve what you intend to do.

Upvotes: 2

Fredrik Pihl
Fredrik Pihl

Reputation: 45634

Use this to generate a random string

import os
random_string = os.urandom(string_length)

To loop over a file line by line, do

with open('file') as fd:
    for line in fd:
        # do stuff

No need to close the file handle

use split to well, split on whitespace and place the result in an array (indexing starts at 0) Read more at docs.python.org

Please update your question with some code when you have gotten that far... Good luck

Upvotes: 2

Related Questions