How to edit a text file in a folder? - python

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

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'

Related

Python Write File Path into Files

I have the following problem:
I have a folder with files.
I want to write into those files their respective file path + filename (home/text.txt) .
How can I achieve this in python?
Thanks in advance for your time and help!
with open('FOLDER_NAME/FILE_NAME','w+') as f:
Assuming the python file is in the same path as the folder.
You can use:
..
to move back a directory.
file = open("path", "w+")
file.write("string you want to write in there")
file.close
With w+ it is for reading and writing to a file, existing data will be overwritten.
Of course, as Landon said, you can simply do this by using with, which will close the file for you after you are done writing to it:
with open("path") as file:
file.write("same string here")
This second snippet only takes up 2 lines, and it is the common way of opening a file.
However if you want append to instead of overwriting a file, use a+ this will open and allow you to read and append. Which means existing data will still be there, whatever you write will be added to the end. The file will also be created if it doesn’t exist.
Read more:
https://www.geeksforgeeks.org/reading-writing-text-files-python/
Correct way to write line to file?

How can I write on new lines in a text file while preserving old ones

When I open a text file and write in it and at the end of the program close it, the lines stay in the text file. When i reopen that program, rather than writing on a new set of lines, it overwrites what is already there. I want to keep both pieces of text, it is for data logging. Any ideas on how to fix this.
You should use the a mode, like this:
with open("file","a") as f:
f.write("Something")
This will append to the file instead of overwriting it.

Printing a txt file inside python shell

I have an assignment for class that has me transfer txt data from excel and execute in python. But every time I run it, only hex is displayed. I was wondering how to have the data displayed in ascii in the shell. This is the code I have so far. Is it possible to print it out in ascii in the shell?
infile = open("data.txt", 'r')
listName = [line.rstrip() for line in infile]
print (listName)
infile.close()
The reason its not working is because you are opening an Excel file - which is in a special format and is not a plain text file.
You can test this by yourself by opening the file in a text editor like Notepad; and you'll see the contents aren't in text.
To open the file and read its contents in Python you will need to do one of these two things:
Open the file in Excel, then save it as a text file (or a comma separated file CSV). Keep in mind if you do this, then you can only save one sheet at a time.
Use a module like pyexcel which will allow you to read the Excel file correctly in Python.
Just opening the file as plain text (or changing its extension) doesn't convert it.

How to upload a .csv file changing the delimiter?

I'm using Python, and with the library gdata I can upload a .csv file, but the delimiter stays as default, that is comma (","). How can I do to change the delimiter to, for example, ";" ?
What I want is, from Python, change the delimiter of an uploading file. I don't want to change the "," to ";", I want to change the delimiter.
You could open the .csv using excel, then it knows its a csv (Comma Delimeted file) but you can set other things to 'delimit' the file by such as spaces etc.
Edit: Sorry, should've mentioned, don't open the file using the 'open with' method, open Excel first, then open the file from within Excel. This should open the 'Text Import Wizard' - Where you can choose what to delimt the file with such as tab,semicolon,comma,space etc.
I am assuming you really need to select this delimiter through gdata, right?
Otherwise you can easily change the delimiter in a shell with something like:
cat my_csv.csv | tr ',' ';' > my_csv_other_delimiter.csv
You can also easily replace these symbols in your python code. It could be an overload if you receive your csv files from somewhere else and you cannot control the symbol you use as a delimiter, but if there is no choice that could be an option.

reading from multiple txt files - strip data and save to xls

i'm very new to python, so far i have written the following code below, which allows me to search for text files in a folder, then read all the lines from it, open an excel file and save the read lines in it. (Im still unsure whether this does it for all the text files one by one)
Having run this, i only see the file text data being read and saved into the excel file (first column). Or it could be that it is overwriting the the data from multiple text files into the same column until it finishes.
Could anyone point me in the right direction on how to get it to write the stripped data to the next available column in excel through each text file?
import os
import glob
list_of_files = glob.glob('./*.txt')
for fileName in list_of_files:
fin = open( fileName, "r" )
data_list = fin.readlines()
fin.close() # closes file
del data_list[0:17]
del data_list[1:27] # [*:*]
fout = open("stripD.xls", "w")
fout.writelines(data_list)
fout.flush()
fout.close()
Can be condensed in
import glob
list_of_files = glob.glob('./*.txt')
with open("stripD.xls", "w") as fout:
for fileName in list_of_files:
data_list = open( fileName, "r" ).readlines()
fout.write(data_list[17])
fout.writelines(data_list[44:])
Are you aware that writelines() doesn't introduce newlines ? readlines() keeps newlines during a reading, so there are newlines present in the elements of data_list written in the file by writelines() , but this latter doesn't introduce newlines itself
You may like to check this and for simple needs also csv.
These lines are "interesting":
del data_list[0:17]
del data_list[1:27] # [*:*]
You are deleting as many of the first 17 lines of your input file as exist, keeping the 18th (if it exists), deleting another 26 (if they exist), and keeping any following lines. This is a very unusual procedure, and is not mentioned at all in your description of what you are trying to do.
Secondly, you are writing the output lines (if any) from each to the same output file. At the end of the script, the output file will contain data from only the last input file. Don't change your code to use append mode ... opening and closing the same file all the time just to append records is very wasteful, and only justified if you have a real need to make sure that the data is flushed to disk in case of a power or other failure. Open your output file once, before you start reading files, and close it once when you have finished with all the input files.
Thirdly, any old arbitrary text file doesn't become an "excel file" just because you have named it "something.xls". You should write it with the csv module and name it "something.csv". If you want more control over how Excel will interpret it, write an xls file using xlwt.
Fourthly, you mention "column" several times, but as you have not given any details about how your input lines are to be split into "columns", it is rather difficult to guess what you mean by "next available column". It is even possible to suspect that you are confusing columns and rows ... assuming less than 43 lines in each input file, the 18th ROW of the last input file will be all you will see in the output file.

Categories