80% of the time the thermocouple causes this problem. When lighting the pilot, if the thermocouple is not directly in the flame it doesn’t get hot enough to allow it to open the safety valve. If it is directly in the flame and it won’t stay lit then the thermocouple is probably defective and needs to be replaced, Keep in mind that some safety valves have the thermocouple permanently attached so the entire valve must be replaced.
If you’ve replaced the thermocouple and attempt to light the pilot and it still will not stay lit then the safety valve is defective. Remember to check the type of safety valve you have to get the correct replacement. For correct identification procedures check out this Tech Talk post.
When working on any type of gas equipment always remember to shut off the gas!