'How to edit a text file in a folder?

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.)



Solution 1:[1]

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'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1