0

This is the file set up:

text_file.csv
Folder----code.py

What I want do do is have code.py write "bob" in text_file.csv.

(Note: a .csv file is just a text file.)

martineau
  • 119,623
  • 25
  • 170
  • 301
  • csv and txt are not the same thing. for csv use `csv.writer()` and for txt use `fileID.write()`. You may also need `os.chdir()` to get to the file. – Eli Harold Feb 01 '22 at 19:47
  • 1
    Does this help? https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file/6160082#6160082 – Wups Feb 01 '22 at 19:52
  • What exactly do you mean by 'editing' a file? Overwrite a few sections? Append? Truncate to zero? That will determine which mode you `open()` in, and whether you `read()` before `write()`ing. – smci Feb 01 '22 at 19:56
  • While CSV files *are* text files, their contents is formatted in a [certain way](https://datatracker.ietf.org/doc/html/rfc4180.html) — which you need to follow if you want it to be (or remain) valid. I strongly suggest you use the [`csv`](https://docs.python.org/3/library/csv.html#module-csv) module to read and write them. – martineau Feb 01 '22 at 19:57
  • @Wups: The answers to the linked question don't really apply to CSV-formatted text files. – martineau Feb 01 '22 at 20:04
  • @Joseph: What exactly do you mean by "edit a text file"? – martineau Feb 01 '22 at 20:05

1 Answers1

0

NOTE: csv file is not equal as text file, csv is a comma-separated-values file, and it is formatted in a different way, you should watch out for these things, for more informations, visit the wikipedia page

if you want to write the content you can use the built-in open function:

open(Path,mode).write(content)

if you want to overwrite the content use 'w' mode:

open("..\\text_file.csv","w").write("bob")

if you want to add it append it, you can use the 'a' mode:

open("..\\text_file.csv",'a').write("bob")

but if you want to add it as a newline, you should add a '\n' in fromt of the "bob"(the text you want to put in):

open("..\\text_file.csv","a").write('\n'+"bob") #adding a newline to 'bob'
XxJames07-
  • 1,833
  • 1
  • 4
  • 17