8

I need to write something into files, which I am passing through command line in python. I am using the below code mycode.py

import csv
import sys

path = sys.argv[1]
row = ['4', ' Danny', ' New York']

with open(r"path" , 'w') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)

When I execute it, the file is not written, but when I hardcode path as

 with open(r"C:\Users\venkat\Desktop\python\sam.csv", 'w') as 
 csvFile:

the file is being written, Please let me know if I am missing anything.

One more requirement is I have to pass only the directory in open, and append some file name. For example: I can pass

C:\Users\venkat\Desktop\python, sam.csv

I have to append to the directory in code.

1
  • 1
    You're passing "path" as a string literal and not as a variable. Try replacing 'r"path"' with just 'path' (without quotes). Commented Nov 14, 2018 at 8:19

4 Answers 4

7

You should use the path variable's value.

Replace

with open(r"path" , 'w') as csvFile:

with

with open(path , 'w') as csvFile:
          ^^^^

If you want to append one file to a directory path, you could use os package.

file_path = os.path.join(path, file)
Sign up to request clarification or add additional context in comments.

3 Comments

well that worked, how can i append file name to path, for example: my path variable be C:\Users\venkat\Desktop\python, i should append sam.csv as file to path.
You could use os package. os.path.join(path, file)
os.path.join(path, "file_name") , file name as string creates a file under my path directory, Thank you so much.
4

Well this worked

import csv
import sys

path = sys.argv[1]
row = ['4', ' Danny', ' New York']

with open(path, 'w') as csvFile:
    writer = csv.writer(csvFile)
    writer.writerow(row)

Comments

0

If you want to append(or write) an existing file,this worked too using format:

path="insert\\pathOf\\file.txt"
with open("{}".format(path),'a') as file:
    file.write("excellent\n") 

The 'a' is for append,so it will add the 'excellent' string to file.txt. If you want to write a new file just put 'w' instead of 'a'.

Using 'w' will overwrite the file.txt if already exists. The \n is for ending in new line so if you run the same code 2 times it will add 'excellent' in two different lines and not side by side.

Comments

-1

You should add curly braces if you want to convert it to raw format

with open(rf"{path}" , 'w') as csvFile:

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.