I need to use a python code without editing it (another's code).
At some point, this code reads the line of a text file to get some file names.
To do so, it uses a line.split()
On the example I was given, I had a file name like /home/directory/fileName
When I do a split on such a line, I get ['/home/directory/fileName\]
The point is the files I work on are located on "My Passport".
I had errors during the execution of the code that are caused by the name of the file.
Indeed, when I tried on python to split the following line: /media/My Passport/directory/fileName, I have ['/media/My', 'Passport/directory/fileName'], so a list with two elements, which the program I have cannot handle. This is because at some point of this code, fileName[0][0] is called, which should be ['/media/My 'Passport/directory/fileName'], but which is ['/media/My', 'Passport/directory/fileName']
I tried to change the name of my device, but it turns out I need to reformat it to do so... which I can't...
Anyone has an idea how I can handle this problem, specifically how I can modify the file names so that, after a line.split(), I get ['/media/My 'Passport/directory/fileName'] ??
Thank you
EDIT
I have a text file in which I have a list of file names with their path
/media/My Passport/fileName1
/media/My Passport/fileName2
/media/My Passport/fileName3
I have a code where I split the lines of this file line.split() to get lists like
['/media/My Passport/fileName1']
I know I can get such lists using line.split(\n), but I have to use line.split()
I am looking for a way to modify the text file so that, when I run line.split(), I get lists like
['/media/My Passport/fileName1']
and not
['/media/My', 'Passport/fileName1']
I have been trying to change the file text using brackets and backslashes :
"/media/My Passport/fileName1"
/media/My\ Passport/fileName1
but the same problem remains
Let us say you have
splitted_result = ['/media/My', 'Passport/fileName1']
Then you can do a simple join
>>> [' '.join(splitted_result)]
['/media/My Passport/fileName1']
This will output a list as its result.
Related
I am relatively new to python and I am making a small game that involves importing each line of the text from a .txt file, so that it can be printed to the user. To do this, I'm using linecache.getline() to get the specific line of the file that I want while not having the whole file stored as a list. However, if I use "\n" to create a new line, then linecache.getline() automatically inserts another backslash to "cancel" it.
For example, if in the text file I write
\nHello,
linecache.getline() will store it in the variable as
\\nHello
which prints as
\nHello.
Is there any way to stop this? I can post my specific code if required.
Any help with file manipulation will be appreciated since I am very new to it and thank you for looking at my question.
This is my carDatabase.txt
CarID:c01 ModelName:honda VehicleType:city Price:20
CarID:c02 ModelName:honda VehicleType:x Price:30
I want to search for the carID and be only able to modify the whole line without interrupting others
my current code is here:
# Converting txt data into a string and modify
carsDatabaseFile = open('carsDatabase.txt', 'r')
allDataFromDatabase = [line.split(',') for line in carsDatabaseFile.readlines()]
Note:
Your question has a couple of issues: your sample from carDatabase.txt looks like it is tab-delimited, but your current code looks like it is splitting the line around the ',' character. This also looks like a place where a list comprehension might be hurting you more than it is helping you. Break that up into a for-loop if you're trying to add some logic to manipulate a single line.
For looking at CSV files, I would highly recommend using pandas for general manipulation of data in comma ceparated as well as a number of other formats.
That said, if you are truly restricted to only using built-in packages, or you are looking at this as a learning exercise, and your goal is to directly manipulate just one line of that file, what you are looking for is the seek method. You can use this in combination with the tell method ( documented just blow seek in the above link ) to find where you are in the file.
Write a for loop to identify which line in the file you are looking for
From there, you can get the output of tell() to find the specific place in the file you are trying to manipulate
Using the output from the above two steps, you can set the file pointer to a specific location using the seek() method (by byte: files are really stored as one dimensional).
You can now use the write() method to directly update the file at the location you determined above.
I'm looking for help in understanding why my name separator script isn't working. I am working through 'Automate the Boring Stuff With Python' and had the opportunity to test some things out at work today. I recognize this probably not the most efficient solution, but I'm trying to put my learning to work.
The Goal
I have an excel file with first and last names in a single cell. I need to separate these into two cells, one for first name and one for last name.
The Process
I began my saving the excel file as a .csv to then open in a text editor.
Used regular expressions to find the full name, grouping first and last names separately. (see the code in link provided)
I copy the raw .csv text to the clipboard using pyperclip (I don't know how to read from files yet.)
I extract the name data using the regex.
I run a for loop which creates a string with first name + ',' + last name + ',' so that excel will put the first and last names in different cells.
I want to end each firstName,lastName, pair with a new line so that my .csv file looks like:
firstname,lastname,
firstname2,lastname2,
etc...
I'm getting stuck on the last step. My for loop gets the firstname,lastname, pairs correct, but when I paste from the clipboard, the newline characters are not inserted. Everything is pasted as one huge string. Since I'm appending a new line character each cycle, shouldn't it paste everything on separate lines? Please help me understand what I'm missing!
Here is a link to my script: https://github.com/RNGeezus/name-separator/blob/master/name_separator.py
Here is what my .csv file looks like (recreated with dummy names to protect peopel's privacy):
my sample
Figured it out! Turns out I needed each pair to be followed by a \r\n. I was doing carriage returns, but no newlines. Doh!
I have a database that contains records of all the budgies in my aviary. It also includes breeding information. I recently made a script in python that prints out the family tree of any specific bird. However, I did this by creating a 2D list in the script file. This means that any changes I make to the database are not reflected in the program. To improve this, I have exported the data to a txt file, with the hope of importing that file into my script as a 2D list.
The text file represents the data delimited by commas, where the first column is the bird's name, the second column is its mother, the third column is its father. For example:
"Myriad","Ruby","Indiana"
"Vanadium","Peeper","Jeckyll"
"Kevin","Vanadium","Manganese"
I've read lots of explanations of how to do this and am currently using the code:
with open("BudgieStock.txt") as textFile:
birdList = [line.split() for line in textFile]
However, if I then print the array it adds an extra single quote around each list:
[[' "Myriad","Ruby","Indiana" '], [' "Vanadium","Peeper","Jeckyll" '], [' "Kevin","Vanadium","Manganese" ']]
This stops my program from working. I've looked everywhere but can't find any explanation of why this is happening or how to stop it.
What I want is simply:
[["Myriad","Ruby","Indiana"], ["Vanadium","Peeper","Jeckyll"], ["Kevin","Vanadium","Manganese"]]
The program worked well when I hardcoded the list into the script file. I tried removing the single quotes using:
[t.replace("'", "") for t in birdList]
But was given the error, "'List' object has no attribute 'replace'".
If anyone can explain why this is happening and how to fix it, I would greatly appreciate it. This is my first time importing files using python (C++ background).
line.split() splits by whitespace. You want to split by commas.
with open("BudgieStock.txt") as textFile:
birdList = [line.split(',') for line in textFile]
Also, you need to get rid of the extraneous quotes as well. I'd recommend just leaving them out of your file entirely, but
with open("BudgieStock.txt") as textFile:
birdList = [[i.strip("\"") for i in line.split(',')] for line in textFile]
would get rid of them too.
I am working with Python 3.3 using PyDev for Eclipse, Alright, so this is my code:
countdata = open(countfilename, 'r')
countlist = countdata.readlines()
print(len(countlist))
genecountline = wordlist(countlist[-1])
print(genecountline)
countfilename refers to a rather lengthy text file of 7847 lines that is generated from a text file using a script given to me by the instructor in my machine learning class (I did have to convert said script to Python 3 using 2to3).
wordlist is a simple function I built that takes a line of text and returns the words in it as a list.
I pull the whole file into a list of lines so that I an refer to specific lines at will for my calculation. Whether I read them in all at once with readlines or iterate over the file and add the lines to the list one by one like this:
countdata = open(countfilename, 'r')
countlist = []
for line in countdata:
countlist.append(line)
doesn't matter. Either way I do it, print(len(countlist)) gives me approximately 7630, I say approximately because sometimes it is as low as 7628 or as high as 7633. The specific line returned by countlist[-1] is always different (the file is built using a generator object, as mentioned my instructor built that script and I am not entirely sure how exactly it works).
genecountline = wordlist(countlist[-1])
print(genecountline)
I put in just to see what python thinks the last line of the file is. And when I open the file in textpad, the line it returns is in fact the line number returned by len(countlist). In other words it appears to be ignoring the last approx. 210 lines of my file. So my question is how do I fix this, and how do I prevent it from doing this again?
If you're not reading from a static text file but from the one that generates each time you run your program, it could be that you don't close that file (in which case everything might not have been written to it). If you don't want to close it, you could flush it (.flush() method).
You should post the code that generates the file.