0

So i need to append to a file in python. This is a random command line input

Example 1:

file1 This is a sentence.

How do i make it so it "This is a sentence" would be appended to file1 not just "This"

Example 2:

file2 A sentence

How do i make it so it "A sentence" would be appended to file2 not just "A"

This is what i have so far. And any random sentence could be appended to the files

with open(input[1],'a') as fileA:
        fileA.write(input[2])

1 Answer 1

2

Pass the second command line arguments as a single argument in the shell:

python /path/to/script.py file1 "This is a sentence."

Alternatively, join the arguments after the filename using str.join:

with open(input[1], 'a') as fileA:
    fileA.write(' '.join(input[2:]))

But the alternative solution will not preserve exact count of spaces / tabs.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I was stuck for ages!

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.