How to add a comma separator to a text file in python
Assuming the original text file is data.txt
f = open('data.txt')
t = open('out.csv','w+')
t.write(f.read().replace(' ',','))
You will find a csv file (you can also create a txt file - just change the file extension as txt) in the current directory with the desired output
Add comma at end of each line in text file from start
You can simply read all lines of your file and rewrite them appending a comma at the end of each line.
First you should read the file and save each of its' lines:
filepath = "myfile.txt"
with open(filepath) as f:
lines = f.read().splitlines()
Now you have created a list with every line in your file. Then, you simply rewrite it and append the comma to each line:
with open(filepath, "w") as f:
for line in lines:
f.write(line + ",\n")
Hope this was helpful!
Adding Commas to Delineate a File using Python
Edit: Fixed the issue caught by @DarryIG.
- Create a list of phrases that need to remain intact. Let's call it
phrase_list
. - Identify a character or string that will never be used in the input file. For example, here I am assuming that an underscore will never be found in the input file and assign it to the variable
forbidden_str
. We could also use something like%$#%$#^%&%_@^
- chances of something like that occurring is very rare. - Replace multiple spaces with single spaces. Then replace spaces in phrases to
_
(forbidden_str). Then replace all spaces with commas. Finally, replace_
s back to spaces.
You could also simplify the reading lines part of your code using readlines()
.
...
phrase_list = ['NO LIMIT']
forbidden_str = "_"
with open(File_Name,'r') as f:
new_lines = f.readlines()
new_lines = new_lines[5:Final_Count]
with open(File_Name,"w") as f:
for line in new_lines:
for phrase in phrase_list:
if phrase in line:
line = line.replace(phrase, phrase.replace(" ", forbidden_str))
line = line.replace(" ", " ") # replaces multiple spaces with single spaces
line = line.replace(" ", ",")
line = line.replace(forbidden_str, " ")
f.write(line)
Output:
2020MAY16,215015,2.0,1004.4,30.0,2.0,2.0,2.0,NO LIMIT,OFF,OFF,OFF,OFF,-25.84,-32.50,CRVBND,N/A,-0.0,28.52,78.54,FCST,GOES16,33.4,
Also, a quick suggestion. It's a good practice to name variables in lower case. For example, final_count
instead of Final_Count
. Upper cases are usually used for classes, instances, etc. It just helps in readability and debugging.
Import .txt file with commas and no spaces between numbers
It seems to be a comma-separated-value file (csv). Use the python csv
module or pandas read_csv
function... Or if you want genfromtxt, you can use the delimiter parameter:
genfromtxt('my_file.txt', delimiter=',')
export a comma-separated string as a text file without auto-formatting it as a CSV
I am not sure if what you need is:
csvList = ','.join(df.ColumnHeader)
where, df is of course your pandas dataframe
Related Topics
How to Check If a String Is Unicode or Ascii
Loop Through Json Data in Python
Convert Tensorflow String to Python String
Convert Numpy.Datetime64 to String Object in Python
How to Modify the Navigation Toolbar Easily in a Matplotlib Figure Window
Loading All Images Using Imread from a Given Folder
Psycopg2 Insert Python Dictionary as Json
Animate a Rotating 3D Graph in Matplotlib
Use Tqdm Progress Bar With Pandas
Splitting Dataframe into Multiple Dataframes
How to Test If a List Contains Another List as a Contiguous Subsequence
How to Enable Autocomplete (Intellisense) for Python Package Modules
In Python, How to Find the Vowels in a Word
Render_Template in Python-Flask Is Not Working
Dividing Each Row by the Previous One
Pyspark - Pass List as Parameter to Udf
Permissionerror: [Errno 13] Permission Denied
I Am Trying to Split a Full Name to First Middle and Last Name in Pandas But I Am Stuck At Replace